1 //===-- DynamicLoaderMacOSXDYLD.cpp -----------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/Breakpoint/StoppointCallbackContext.h"
10 #include "lldb/Core/Debugger.h"
11 #include "lldb/Core/Module.h"
12 #include "lldb/Core/ModuleSpec.h"
13 #include "lldb/Core/PluginManager.h"
14 #include "lldb/Core/Section.h"
15 #include "lldb/Symbol/ClangASTContext.h"
16 #include "lldb/Symbol/Function.h"
17 #include "lldb/Symbol/ObjectFile.h"
18 #include "lldb/Target/ABI.h"
19 #include "lldb/Target/RegisterContext.h"
20 #include "lldb/Target/StackFrame.h"
21 #include "lldb/Target/Target.h"
22 #include "lldb/Target/Thread.h"
23 #include "lldb/Target/ThreadPlanRunToAddress.h"
24 #include "lldb/Utility/DataBuffer.h"
25 #include "lldb/Utility/DataBufferHeap.h"
26 #include "lldb/Utility/Log.h"
27 #include "lldb/Utility/State.h"
28 
29 #include "DynamicLoaderDarwin.h"
30 #include "DynamicLoaderMacOSXDYLD.h"
31 
32 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
33 
34 //#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN
35 #ifdef ENABLE_DEBUG_PRINTF
36 #include <stdio.h>
37 #define DEBUG_PRINTF(fmt, ...) printf(fmt, ##__VA_ARGS__)
38 #else
39 #define DEBUG_PRINTF(fmt, ...)
40 #endif
41 
42 #ifndef __APPLE__
43 #include "Utility/UuidCompatibility.h"
44 #else
45 #include <uuid/uuid.h>
46 #endif
47 
48 using namespace lldb;
49 using namespace lldb_private;
50 
51 // Create an instance of this class. This function is filled into the plugin
52 // info class that gets handed out by the plugin factory and allows the lldb to
53 // instantiate an instance of this class.
54 DynamicLoader *DynamicLoaderMacOSXDYLD::CreateInstance(Process *process,
55                                                        bool force) {
56   bool create = force;
57   if (!create) {
58     create = true;
59     Module *exe_module = process->GetTarget().GetExecutableModulePointer();
60     if (exe_module) {
61       ObjectFile *object_file = exe_module->GetObjectFile();
62       if (object_file) {
63         create = (object_file->GetStrata() == ObjectFile::eStrataUser);
64       }
65     }
66 
67     if (create) {
68       const llvm::Triple &triple_ref =
69           process->GetTarget().GetArchitecture().GetTriple();
70       switch (triple_ref.getOS()) {
71       case llvm::Triple::Darwin:
72       case llvm::Triple::MacOSX:
73       case llvm::Triple::IOS:
74       case llvm::Triple::TvOS:
75       case llvm::Triple::WatchOS:
76       // NEED_BRIDGEOS_TRIPLE case llvm::Triple::BridgeOS:
77         create = triple_ref.getVendor() == llvm::Triple::Apple;
78         break;
79       default:
80         create = false;
81         break;
82       }
83     }
84   }
85 
86   if (UseDYLDSPI(process)) {
87     create = false;
88   }
89 
90   if (create)
91     return new DynamicLoaderMacOSXDYLD(process);
92   return nullptr;
93 }
94 
95 // Constructor
96 DynamicLoaderMacOSXDYLD::DynamicLoaderMacOSXDYLD(Process *process)
97     : DynamicLoaderDarwin(process),
98       m_dyld_all_image_infos_addr(LLDB_INVALID_ADDRESS),
99       m_dyld_all_image_infos(), m_dyld_all_image_infos_stop_id(UINT32_MAX),
100       m_break_id(LLDB_INVALID_BREAK_ID), m_mutex(),
101       m_process_image_addr_is_all_images_infos(false) {}
102 
103 // Destructor
104 DynamicLoaderMacOSXDYLD::~DynamicLoaderMacOSXDYLD() {
105   if (LLDB_BREAK_ID_IS_VALID(m_break_id))
106     m_process->GetTarget().RemoveBreakpointByID(m_break_id);
107 }
108 
109 bool DynamicLoaderMacOSXDYLD::ProcessDidExec() {
110   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
111   bool did_exec = false;
112   if (m_process) {
113     // If we are stopped after an exec, we will have only one thread...
114     if (m_process->GetThreadList().GetSize() == 1) {
115       // We know if a process has exec'ed if our "m_dyld_all_image_infos_addr"
116       // value differs from the Process' image info address. When a process
117       // execs itself it might cause a change if ASLR is enabled.
118       const addr_t shlib_addr = m_process->GetImageInfoAddress();
119       if (m_process_image_addr_is_all_images_infos &&
120           shlib_addr != m_dyld_all_image_infos_addr) {
121         // The image info address from the process is the
122         // 'dyld_all_image_infos' address and it has changed.
123         did_exec = true;
124       } else if (!m_process_image_addr_is_all_images_infos &&
125                  shlib_addr == m_dyld.address) {
126         // The image info address from the process is the mach_header address
127         // for dyld and it has changed.
128         did_exec = true;
129       } else {
130         // ASLR might be disabled and dyld could have ended up in the same
131         // location. We should try and detect if we are stopped at
132         // '_dyld_start'
133         ThreadSP thread_sp(m_process->GetThreadList().GetThreadAtIndex(0));
134         if (thread_sp) {
135           lldb::StackFrameSP frame_sp(thread_sp->GetStackFrameAtIndex(0));
136           if (frame_sp) {
137             const Symbol *symbol =
138                 frame_sp->GetSymbolContext(eSymbolContextSymbol).symbol;
139             if (symbol) {
140               if (symbol->GetName() == "_dyld_start")
141                 did_exec = true;
142             }
143           }
144         }
145       }
146 
147       if (did_exec) {
148         m_libpthread_module_wp.reset();
149         m_pthread_getspecific_addr.Clear();
150       }
151     }
152   }
153   return did_exec;
154 }
155 
156 // Clear out the state of this class.
157 void DynamicLoaderMacOSXDYLD::DoClear() {
158   std::lock_guard<std::recursive_mutex> guard(m_mutex);
159 
160   if (LLDB_BREAK_ID_IS_VALID(m_break_id))
161     m_process->GetTarget().RemoveBreakpointByID(m_break_id);
162 
163   m_dyld_all_image_infos_addr = LLDB_INVALID_ADDRESS;
164   m_dyld_all_image_infos.Clear();
165   m_break_id = LLDB_INVALID_BREAK_ID;
166 }
167 
168 // Check if we have found DYLD yet
169 bool DynamicLoaderMacOSXDYLD::DidSetNotificationBreakpoint() {
170   return LLDB_BREAK_ID_IS_VALID(m_break_id);
171 }
172 
173 void DynamicLoaderMacOSXDYLD::ClearNotificationBreakpoint() {
174   if (LLDB_BREAK_ID_IS_VALID(m_break_id)) {
175     m_process->GetTarget().RemoveBreakpointByID(m_break_id);
176   }
177 }
178 
179 // Try and figure out where dyld is by first asking the Process if it knows
180 // (which currently calls down in the lldb::Process to get the DYLD info
181 // (available on SnowLeopard only). If that fails, then check in the default
182 // addresses.
183 void DynamicLoaderMacOSXDYLD::DoInitialImageFetch() {
184   if (m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS) {
185     // Check the image info addr as it might point to the mach header for dyld,
186     // or it might point to the dyld_all_image_infos struct
187     const addr_t shlib_addr = m_process->GetImageInfoAddress();
188     if (shlib_addr != LLDB_INVALID_ADDRESS) {
189       ByteOrder byte_order =
190           m_process->GetTarget().GetArchitecture().GetByteOrder();
191       uint8_t buf[4];
192       DataExtractor data(buf, sizeof(buf), byte_order, 4);
193       Status error;
194       if (m_process->ReadMemory(shlib_addr, buf, 4, error) == 4) {
195         lldb::offset_t offset = 0;
196         uint32_t magic = data.GetU32(&offset);
197         switch (magic) {
198         case llvm::MachO::MH_MAGIC:
199         case llvm::MachO::MH_MAGIC_64:
200         case llvm::MachO::MH_CIGAM:
201         case llvm::MachO::MH_CIGAM_64:
202           m_process_image_addr_is_all_images_infos = false;
203           ReadDYLDInfoFromMemoryAndSetNotificationCallback(shlib_addr);
204           return;
205 
206         default:
207           break;
208         }
209       }
210       // Maybe it points to the all image infos?
211       m_dyld_all_image_infos_addr = shlib_addr;
212       m_process_image_addr_is_all_images_infos = true;
213     }
214   }
215 
216   if (m_dyld_all_image_infos_addr != LLDB_INVALID_ADDRESS) {
217     if (ReadAllImageInfosStructure()) {
218       if (m_dyld_all_image_infos.dyldImageLoadAddress != LLDB_INVALID_ADDRESS)
219         ReadDYLDInfoFromMemoryAndSetNotificationCallback(
220             m_dyld_all_image_infos.dyldImageLoadAddress);
221       else
222         ReadDYLDInfoFromMemoryAndSetNotificationCallback(
223             m_dyld_all_image_infos_addr & 0xfffffffffff00000ull);
224       return;
225     }
226   }
227 
228   // Check some default values
229   Module *executable = m_process->GetTarget().GetExecutableModulePointer();
230 
231   if (executable) {
232     const ArchSpec &exe_arch = executable->GetArchitecture();
233     if (exe_arch.GetAddressByteSize() == 8) {
234       ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x7fff5fc00000ull);
235     } else if (exe_arch.GetMachine() == llvm::Triple::arm ||
236                exe_arch.GetMachine() == llvm::Triple::thumb ||
237                exe_arch.GetMachine() == llvm::Triple::aarch64 ||
238                exe_arch.GetMachine() == llvm::Triple::aarch64_32) {
239       ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x2fe00000);
240     } else {
241       ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x8fe00000);
242     }
243   }
244   return;
245 }
246 
247 // Assume that dyld is in memory at ADDR and try to parse it's load commands
248 bool DynamicLoaderMacOSXDYLD::ReadDYLDInfoFromMemoryAndSetNotificationCallback(
249     lldb::addr_t addr) {
250   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
251   DataExtractor data; // Load command data
252   static ConstString g_dyld_all_image_infos("dyld_all_image_infos");
253   if (ReadMachHeader(addr, &m_dyld.header, &data)) {
254     if (m_dyld.header.filetype == llvm::MachO::MH_DYLINKER) {
255       m_dyld.address = addr;
256       ModuleSP dyld_module_sp;
257       if (ParseLoadCommands(data, m_dyld, &m_dyld.file_spec)) {
258         if (m_dyld.file_spec) {
259           UpdateDYLDImageInfoFromNewImageInfo(m_dyld);
260         }
261       }
262       dyld_module_sp = GetDYLDModule();
263 
264       Target &target = m_process->GetTarget();
265 
266       if (m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS &&
267           dyld_module_sp.get()) {
268         const Symbol *symbol = dyld_module_sp->FindFirstSymbolWithNameAndType(
269             g_dyld_all_image_infos, eSymbolTypeData);
270         if (symbol)
271           m_dyld_all_image_infos_addr = symbol->GetLoadAddress(&target);
272       }
273 
274       // Update all image infos
275       InitializeFromAllImageInfos();
276 
277       // If we didn't have an executable before, but now we do, then the dyld
278       // module shared pointer might be unique and we may need to add it again
279       // (since Target::SetExecutableModule() will clear the images). So append
280       // the dyld module back to the list if it is
281       /// unique!
282       if (dyld_module_sp) {
283         target.GetImages().AppendIfNeeded(dyld_module_sp);
284 
285         // At this point we should have read in dyld's module, and so we should
286         // set breakpoints in it:
287         ModuleList modules;
288         modules.Append(dyld_module_sp);
289         target.ModulesDidLoad(modules);
290         SetDYLDModule(dyld_module_sp);
291       }
292 
293       return true;
294     }
295   }
296   return false;
297 }
298 
299 bool DynamicLoaderMacOSXDYLD::NeedToDoInitialImageFetch() {
300   return m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS;
301 }
302 
303 // Static callback function that gets called when our DYLD notification
304 // breakpoint gets hit. We update all of our image infos and then let our super
305 // class DynamicLoader class decide if we should stop or not (based on global
306 // preference).
307 bool DynamicLoaderMacOSXDYLD::NotifyBreakpointHit(
308     void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
309     lldb::user_id_t break_loc_id) {
310   // Let the event know that the images have changed
311   // DYLD passes three arguments to the notification breakpoint.
312   // Arg1: enum dyld_image_mode mode - 0 = adding, 1 = removing Arg2: uint32_t
313   // infoCount        - Number of shared libraries added Arg3: dyld_image_info
314   // info[]    - Array of structs of the form:
315   //                                     const struct mach_header
316   //                                     *imageLoadAddress
317   //                                     const char               *imageFilePath
318   //                                     uintptr_t imageFileModDate (a time_t)
319 
320   DynamicLoaderMacOSXDYLD *dyld_instance = (DynamicLoaderMacOSXDYLD *)baton;
321 
322   // First step is to see if we've already initialized the all image infos.  If
323   // we haven't then this function will do so and return true.  In the course
324   // of initializing the all_image_infos it will read the complete current
325   // state, so we don't need to figure out what has changed from the data
326   // passed in to us.
327 
328   ExecutionContext exe_ctx(context->exe_ctx_ref);
329   Process *process = exe_ctx.GetProcessPtr();
330 
331   // This is a sanity check just in case this dyld_instance is an old dyld
332   // plugin's breakpoint still lying around.
333   if (process != dyld_instance->m_process)
334     return false;
335 
336   if (dyld_instance->InitializeFromAllImageInfos())
337     return dyld_instance->GetStopWhenImagesChange();
338 
339   const lldb::ABISP &abi = process->GetABI();
340   if (abi) {
341     // Build up the value array to store the three arguments given above, then
342     // get the values from the ABI:
343 
344     ClangASTContext *clang_ast_context =
345         process->GetTarget().GetScratchClangASTContext();
346     ValueList argument_values;
347     Value input_value;
348 
349     CompilerType clang_void_ptr_type =
350         clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
351     CompilerType clang_uint32_type =
352         clang_ast_context->GetBuiltinTypeForEncodingAndBitSize(
353             lldb::eEncodingUint, 32);
354     input_value.SetValueType(Value::eValueTypeScalar);
355     input_value.SetCompilerType(clang_uint32_type);
356     //        input_value.SetContext (Value::eContextTypeClangType,
357     //        clang_uint32_type);
358     argument_values.PushValue(input_value);
359     argument_values.PushValue(input_value);
360     input_value.SetCompilerType(clang_void_ptr_type);
361     //        input_value.SetContext (Value::eContextTypeClangType,
362     //        clang_void_ptr_type);
363     argument_values.PushValue(input_value);
364 
365     if (abi->GetArgumentValues(exe_ctx.GetThreadRef(), argument_values)) {
366       uint32_t dyld_mode =
367           argument_values.GetValueAtIndex(0)->GetScalar().UInt(-1);
368       if (dyld_mode != static_cast<uint32_t>(-1)) {
369         // Okay the mode was right, now get the number of elements, and the
370         // array of new elements...
371         uint32_t image_infos_count =
372             argument_values.GetValueAtIndex(1)->GetScalar().UInt(-1);
373         if (image_infos_count != static_cast<uint32_t>(-1)) {
374           // Got the number added, now go through the array of added elements,
375           // putting out the mach header address, and adding the image. Note,
376           // I'm not putting in logging here, since the AddModules &
377           // RemoveModules functions do all the logging internally.
378 
379           lldb::addr_t image_infos_addr =
380               argument_values.GetValueAtIndex(2)->GetScalar().ULongLong();
381           if (dyld_mode == 0) {
382             // This is add:
383             dyld_instance->AddModulesUsingImageInfosAddress(image_infos_addr,
384                                                             image_infos_count);
385           } else {
386             // This is remove:
387             dyld_instance->RemoveModulesUsingImageInfosAddress(
388                 image_infos_addr, image_infos_count);
389           }
390         }
391       }
392     }
393   } else {
394     process->GetTarget().GetDebugger().GetAsyncErrorStream()->Printf(
395         "No ABI plugin located for triple %s -- shared libraries will not be "
396         "registered!\n",
397         process->GetTarget().GetArchitecture().GetTriple().getTriple().c_str());
398   }
399 
400   // Return true to stop the target, false to just let the target run
401   return dyld_instance->GetStopWhenImagesChange();
402 }
403 
404 bool DynamicLoaderMacOSXDYLD::ReadAllImageInfosStructure() {
405   std::lock_guard<std::recursive_mutex> guard(m_mutex);
406 
407   // the all image infos is already valid for this process stop ID
408   if (m_process->GetStopID() == m_dyld_all_image_infos_stop_id)
409     return true;
410 
411   m_dyld_all_image_infos.Clear();
412   if (m_dyld_all_image_infos_addr != LLDB_INVALID_ADDRESS) {
413     ByteOrder byte_order =
414         m_process->GetTarget().GetArchitecture().GetByteOrder();
415     uint32_t addr_size =
416         m_process->GetTarget().GetArchitecture().GetAddressByteSize();
417 
418     uint8_t buf[256];
419     DataExtractor data(buf, sizeof(buf), byte_order, addr_size);
420     lldb::offset_t offset = 0;
421 
422     const size_t count_v2 = sizeof(uint32_t) + // version
423                             sizeof(uint32_t) + // infoArrayCount
424                             addr_size +        // infoArray
425                             addr_size +        // notification
426                             addr_size + // processDetachedFromSharedRegion +
427                                         // libSystemInitialized + pad
428                             addr_size;  // dyldImageLoadAddress
429     const size_t count_v11 = count_v2 + addr_size +  // jitInfo
430                              addr_size +             // dyldVersion
431                              addr_size +             // errorMessage
432                              addr_size +             // terminationFlags
433                              addr_size +             // coreSymbolicationShmPage
434                              addr_size +             // systemOrderFlag
435                              addr_size +             // uuidArrayCount
436                              addr_size +             // uuidArray
437                              addr_size +             // dyldAllImageInfosAddress
438                              addr_size +             // initialImageCount
439                              addr_size +             // errorKind
440                              addr_size +             // errorClientOfDylibPath
441                              addr_size +             // errorTargetDylibPath
442                              addr_size;              // errorSymbol
443     const size_t count_v13 = count_v11 + addr_size + // sharedCacheSlide
444                              sizeof(uuid_t);         // sharedCacheUUID
445     UNUSED_IF_ASSERT_DISABLED(count_v13);
446     assert(sizeof(buf) >= count_v13);
447 
448     Status error;
449     if (m_process->ReadMemory(m_dyld_all_image_infos_addr, buf, 4, error) ==
450         4) {
451       m_dyld_all_image_infos.version = data.GetU32(&offset);
452       // If anything in the high byte is set, we probably got the byte order
453       // incorrect (the process might not have it set correctly yet due to
454       // attaching to a program without a specified file).
455       if (m_dyld_all_image_infos.version & 0xff000000) {
456         // We have guessed the wrong byte order. Swap it and try reading the
457         // version again.
458         if (byte_order == eByteOrderLittle)
459           byte_order = eByteOrderBig;
460         else
461           byte_order = eByteOrderLittle;
462 
463         data.SetByteOrder(byte_order);
464         offset = 0;
465         m_dyld_all_image_infos.version = data.GetU32(&offset);
466       }
467     } else {
468       return false;
469     }
470 
471     const size_t count =
472         (m_dyld_all_image_infos.version >= 11) ? count_v11 : count_v2;
473 
474     const size_t bytes_read =
475         m_process->ReadMemory(m_dyld_all_image_infos_addr, buf, count, error);
476     if (bytes_read == count) {
477       offset = 0;
478       m_dyld_all_image_infos.version = data.GetU32(&offset);
479       m_dyld_all_image_infos.dylib_info_count = data.GetU32(&offset);
480       m_dyld_all_image_infos.dylib_info_addr = data.GetPointer(&offset);
481       m_dyld_all_image_infos.notification = data.GetPointer(&offset);
482       m_dyld_all_image_infos.processDetachedFromSharedRegion =
483           data.GetU8(&offset);
484       m_dyld_all_image_infos.libSystemInitialized = data.GetU8(&offset);
485       // Adjust for padding.
486       offset += addr_size - 2;
487       m_dyld_all_image_infos.dyldImageLoadAddress = data.GetPointer(&offset);
488       if (m_dyld_all_image_infos.version >= 11) {
489         offset += addr_size * 8;
490         uint64_t dyld_all_image_infos_addr = data.GetPointer(&offset);
491 
492         // When we started, we were given the actual address of the
493         // all_image_infos struct (probably via TASK_DYLD_INFO) in memory -
494         // this address is stored in m_dyld_all_image_infos_addr and is the
495         // most accurate address we have.
496 
497         // We read the dyld_all_image_infos struct from memory; it contains its
498         // own address. If the address in the struct does not match the actual
499         // address, the dyld we're looking at has been loaded at a different
500         // location (slid) from where it intended to load.  The addresses in
501         // the dyld_all_image_infos struct are the original, non-slid
502         // addresses, and need to be adjusted.  Most importantly the address of
503         // dyld and the notification address need to be adjusted.
504 
505         if (dyld_all_image_infos_addr != m_dyld_all_image_infos_addr) {
506           uint64_t image_infos_offset =
507               dyld_all_image_infos_addr -
508               m_dyld_all_image_infos.dyldImageLoadAddress;
509           uint64_t notification_offset =
510               m_dyld_all_image_infos.notification -
511               m_dyld_all_image_infos.dyldImageLoadAddress;
512           m_dyld_all_image_infos.dyldImageLoadAddress =
513               m_dyld_all_image_infos_addr - image_infos_offset;
514           m_dyld_all_image_infos.notification =
515               m_dyld_all_image_infos.dyldImageLoadAddress + notification_offset;
516         }
517       }
518       m_dyld_all_image_infos_stop_id = m_process->GetStopID();
519       return true;
520     }
521   }
522   return false;
523 }
524 
525 bool DynamicLoaderMacOSXDYLD::AddModulesUsingImageInfosAddress(
526     lldb::addr_t image_infos_addr, uint32_t image_infos_count) {
527   ImageInfo::collection image_infos;
528   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
529   LLDB_LOGF(log, "Adding %d modules.\n", image_infos_count);
530 
531   std::lock_guard<std::recursive_mutex> guard(m_mutex);
532   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
533   if (m_process->GetStopID() == m_dyld_image_infos_stop_id)
534     return true;
535 
536   StructuredData::ObjectSP image_infos_json_sp =
537       m_process->GetLoadedDynamicLibrariesInfos(image_infos_addr,
538                                                 image_infos_count);
539   if (image_infos_json_sp.get() && image_infos_json_sp->GetAsDictionary() &&
540       image_infos_json_sp->GetAsDictionary()->HasKey("images") &&
541       image_infos_json_sp->GetAsDictionary()
542           ->GetValueForKey("images")
543           ->GetAsArray() &&
544       image_infos_json_sp->GetAsDictionary()
545               ->GetValueForKey("images")
546               ->GetAsArray()
547               ->GetSize() == image_infos_count) {
548     bool return_value = false;
549     if (JSONImageInformationIntoImageInfo(image_infos_json_sp, image_infos)) {
550       UpdateSpecialBinariesFromNewImageInfos(image_infos);
551       return_value = AddModulesUsingImageInfos(image_infos);
552     }
553     m_dyld_image_infos_stop_id = m_process->GetStopID();
554     return return_value;
555   }
556 
557   if (!ReadImageInfos(image_infos_addr, image_infos_count, image_infos))
558     return false;
559 
560   UpdateImageInfosHeaderAndLoadCommands(image_infos, image_infos_count, false);
561   bool return_value = AddModulesUsingImageInfos(image_infos);
562   m_dyld_image_infos_stop_id = m_process->GetStopID();
563   return return_value;
564 }
565 
566 bool DynamicLoaderMacOSXDYLD::RemoveModulesUsingImageInfosAddress(
567     lldb::addr_t image_infos_addr, uint32_t image_infos_count) {
568   ImageInfo::collection image_infos;
569   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
570 
571   std::lock_guard<std::recursive_mutex> guard(m_mutex);
572   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
573   if (m_process->GetStopID() == m_dyld_image_infos_stop_id)
574     return true;
575 
576   // First read in the image_infos for the removed modules, and their headers &
577   // load commands.
578   if (!ReadImageInfos(image_infos_addr, image_infos_count, image_infos)) {
579     if (log)
580       log->PutCString("Failed reading image infos array.");
581     return false;
582   }
583 
584   LLDB_LOGF(log, "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       LLDB_LOGF(log, "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             LLDB_LOGF(log, "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         LLDB_LOGF(log, "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           LLDB_LOGF(log, "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   LLDB_LOGF(log,
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,
981             m_dyld_all_image_infos.dylib_info_count,
982             (uint64_t)m_dyld_all_image_infos.dylib_info_addr,
983             (uint64_t)m_dyld_all_image_infos.notification);
984   size_t i;
985   const size_t count = m_dyld_image_infos.size();
986   if (count > 0) {
987     log->PutCString("Loaded:");
988     for (i = 0; i < count; i++)
989       m_dyld_image_infos[i].PutToLog(log);
990   }
991 }
992 
993 bool DynamicLoaderMacOSXDYLD::SetNotificationBreakpoint() {
994   DEBUG_PRINTF("DynamicLoaderMacOSXDYLD::%s() process state = %s\n",
995                __FUNCTION__, StateAsCString(m_process->GetState()));
996   if (m_break_id == LLDB_INVALID_BREAK_ID) {
997     if (m_dyld_all_image_infos.notification != LLDB_INVALID_ADDRESS) {
998       Address so_addr;
999       // Set the notification breakpoint and install a breakpoint callback
1000       // function that will get called each time the breakpoint gets hit. We
1001       // will use this to track when shared libraries get loaded/unloaded.
1002       bool resolved = m_process->GetTarget().ResolveLoadAddress(
1003           m_dyld_all_image_infos.notification, so_addr);
1004       if (!resolved) {
1005         ModuleSP dyld_module_sp = GetDYLDModule();
1006         if (dyld_module_sp) {
1007           std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
1008 
1009           UpdateImageLoadAddress(dyld_module_sp.get(), m_dyld);
1010           resolved = m_process->GetTarget().ResolveLoadAddress(
1011               m_dyld_all_image_infos.notification, so_addr);
1012         }
1013       }
1014 
1015       if (resolved) {
1016         Breakpoint *dyld_break =
1017             m_process->GetTarget().CreateBreakpoint(so_addr, true, false).get();
1018         dyld_break->SetCallback(DynamicLoaderMacOSXDYLD::NotifyBreakpointHit,
1019                                 this, true);
1020         dyld_break->SetBreakpointKind("shared-library-event");
1021         m_break_id = dyld_break->GetID();
1022       }
1023     }
1024   }
1025   return m_break_id != LLDB_INVALID_BREAK_ID;
1026 }
1027 
1028 Status DynamicLoaderMacOSXDYLD::CanLoadImage() {
1029   Status error;
1030   // In order for us to tell if we can load a shared library we verify that the
1031   // dylib_info_addr isn't zero (which means no shared libraries have been set
1032   // yet, or dyld is currently mucking with the shared library list).
1033   if (ReadAllImageInfosStructure()) {
1034     // TODO: also check the _dyld_global_lock_held variable in
1035     // libSystem.B.dylib?
1036     // TODO: check the malloc lock?
1037     // TODO: check the objective C lock?
1038     if (m_dyld_all_image_infos.dylib_info_addr != 0)
1039       return error; // Success
1040   }
1041 
1042   error.SetErrorString("unsafe to load or unload shared libraries");
1043   return error;
1044 }
1045 
1046 bool DynamicLoaderMacOSXDYLD::GetSharedCacheInformation(
1047     lldb::addr_t &base_address, UUID &uuid, LazyBool &using_shared_cache,
1048     LazyBool &private_shared_cache) {
1049   base_address = LLDB_INVALID_ADDRESS;
1050   uuid.Clear();
1051   using_shared_cache = eLazyBoolCalculate;
1052   private_shared_cache = eLazyBoolCalculate;
1053 
1054   if (m_process) {
1055     addr_t all_image_infos = m_process->GetImageInfoAddress();
1056 
1057     // The address returned by GetImageInfoAddress may be the address of dyld
1058     // (don't want) or it may be the address of the dyld_all_image_infos
1059     // structure (want). The first four bytes will be either the version field
1060     // (all_image_infos) or a Mach-O file magic constant. Version 13 and higher
1061     // of dyld_all_image_infos is required to get the sharedCacheUUID field.
1062 
1063     Status err;
1064     uint32_t version_or_magic =
1065         m_process->ReadUnsignedIntegerFromMemory(all_image_infos, 4, -1, err);
1066     if (version_or_magic != static_cast<uint32_t>(-1) &&
1067         version_or_magic != llvm::MachO::MH_MAGIC &&
1068         version_or_magic != llvm::MachO::MH_CIGAM &&
1069         version_or_magic != llvm::MachO::MH_MAGIC_64 &&
1070         version_or_magic != llvm::MachO::MH_CIGAM_64 &&
1071         version_or_magic >= 13) {
1072       addr_t sharedCacheUUID_address = LLDB_INVALID_ADDRESS;
1073       int wordsize = m_process->GetAddressByteSize();
1074       if (wordsize == 8) {
1075         sharedCacheUUID_address =
1076             all_image_infos + 160; // sharedCacheUUID <mach-o/dyld_images.h>
1077       }
1078       if (wordsize == 4) {
1079         sharedCacheUUID_address =
1080             all_image_infos + 84; // sharedCacheUUID <mach-o/dyld_images.h>
1081       }
1082       if (sharedCacheUUID_address != LLDB_INVALID_ADDRESS) {
1083         uuid_t shared_cache_uuid;
1084         if (m_process->ReadMemory(sharedCacheUUID_address, shared_cache_uuid,
1085                                   sizeof(uuid_t), err) == sizeof(uuid_t)) {
1086           uuid = UUID::fromOptionalData(shared_cache_uuid, 16);
1087           if (uuid.IsValid()) {
1088             using_shared_cache = eLazyBoolYes;
1089           }
1090         }
1091 
1092         if (version_or_magic >= 15) {
1093           // The sharedCacheBaseAddress field is the next one in the
1094           // dyld_all_image_infos struct.
1095           addr_t sharedCacheBaseAddr_address = sharedCacheUUID_address + 16;
1096           Status error;
1097           base_address = m_process->ReadUnsignedIntegerFromMemory(
1098               sharedCacheBaseAddr_address, wordsize, LLDB_INVALID_ADDRESS,
1099               error);
1100           if (error.Fail())
1101             base_address = LLDB_INVALID_ADDRESS;
1102         }
1103 
1104         return true;
1105       }
1106 
1107       //
1108       // add
1109       // NB: sharedCacheBaseAddress is the next field in dyld_all_image_infos
1110       // after
1111       // sharedCacheUUID -- that is, 16 bytes after it, if we wanted to fetch
1112       // it.
1113     }
1114   }
1115   return false;
1116 }
1117 
1118 void DynamicLoaderMacOSXDYLD::Initialize() {
1119   PluginManager::RegisterPlugin(GetPluginNameStatic(),
1120                                 GetPluginDescriptionStatic(), CreateInstance);
1121 }
1122 
1123 void DynamicLoaderMacOSXDYLD::Terminate() {
1124   PluginManager::UnregisterPlugin(CreateInstance);
1125 }
1126 
1127 lldb_private::ConstString DynamicLoaderMacOSXDYLD::GetPluginNameStatic() {
1128   static ConstString g_name("macosx-dyld");
1129   return g_name;
1130 }
1131 
1132 const char *DynamicLoaderMacOSXDYLD::GetPluginDescriptionStatic() {
1133   return "Dynamic loader plug-in that watches for shared library loads/unloads "
1134          "in MacOSX user processes.";
1135 }
1136 
1137 // PluginInterface protocol
1138 lldb_private::ConstString DynamicLoaderMacOSXDYLD::GetPluginName() {
1139   return GetPluginNameStatic();
1140 }
1141 
1142 uint32_t DynamicLoaderMacOSXDYLD::GetPluginVersion() { return 1; }
1143 
1144 uint32_t DynamicLoaderMacOSXDYLD::AddrByteSize() {
1145   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
1146 
1147   switch (m_dyld.header.magic) {
1148   case llvm::MachO::MH_MAGIC:
1149   case llvm::MachO::MH_CIGAM:
1150     return 4;
1151 
1152   case llvm::MachO::MH_MAGIC_64:
1153   case llvm::MachO::MH_CIGAM_64:
1154     return 8;
1155 
1156   default:
1157     break;
1158   }
1159   return 0;
1160 }
1161 
1162 lldb::ByteOrder DynamicLoaderMacOSXDYLD::GetByteOrderFromMagic(uint32_t magic) {
1163   switch (magic) {
1164   case llvm::MachO::MH_MAGIC:
1165   case llvm::MachO::MH_MAGIC_64:
1166     return endian::InlHostByteOrder();
1167 
1168   case llvm::MachO::MH_CIGAM:
1169   case llvm::MachO::MH_CIGAM_64:
1170     if (endian::InlHostByteOrder() == lldb::eByteOrderBig)
1171       return lldb::eByteOrderLittle;
1172     else
1173       return lldb::eByteOrderBig;
1174 
1175   default:
1176     break;
1177   }
1178   return lldb::eByteOrderInvalid;
1179 }
1180