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       ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x2fe00000);
239     } else {
240       ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x8fe00000);
241     }
242   }
243   return;
244 }
245 
246 // Assume that dyld is in memory at ADDR and try to parse it's load commands
247 bool DynamicLoaderMacOSXDYLD::ReadDYLDInfoFromMemoryAndSetNotificationCallback(
248     lldb::addr_t addr) {
249   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
250   DataExtractor data; // Load command data
251   static ConstString g_dyld_all_image_infos("dyld_all_image_infos");
252   if (ReadMachHeader(addr, &m_dyld.header, &data)) {
253     if (m_dyld.header.filetype == llvm::MachO::MH_DYLINKER) {
254       m_dyld.address = addr;
255       ModuleSP dyld_module_sp;
256       if (ParseLoadCommands(data, m_dyld, &m_dyld.file_spec)) {
257         if (m_dyld.file_spec) {
258           UpdateDYLDImageInfoFromNewImageInfo(m_dyld);
259         }
260       }
261       dyld_module_sp = GetDYLDModule();
262 
263       Target &target = m_process->GetTarget();
264 
265       if (m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS &&
266           dyld_module_sp.get()) {
267         const Symbol *symbol = dyld_module_sp->FindFirstSymbolWithNameAndType(
268             g_dyld_all_image_infos, eSymbolTypeData);
269         if (symbol)
270           m_dyld_all_image_infos_addr = symbol->GetLoadAddress(&target);
271       }
272 
273       // Update all image infos
274       InitializeFromAllImageInfos();
275 
276       // If we didn't have an executable before, but now we do, then the dyld
277       // module shared pointer might be unique and we may need to add it again
278       // (since Target::SetExecutableModule() will clear the images). So append
279       // the dyld module back to the list if it is
280       /// unique!
281       if (dyld_module_sp) {
282         target.GetImages().AppendIfNeeded(dyld_module_sp);
283 
284         // At this point we should have read in dyld's module, and so we should
285         // set breakpoints in it:
286         ModuleList modules;
287         modules.Append(dyld_module_sp);
288         target.ModulesDidLoad(modules);
289         SetDYLDModule(dyld_module_sp);
290       }
291 
292       return true;
293     }
294   }
295   return false;
296 }
297 
298 bool DynamicLoaderMacOSXDYLD::NeedToDoInitialImageFetch() {
299   return m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS;
300 }
301 
302 // Static callback function that gets called when our DYLD notification
303 // breakpoint gets hit. We update all of our image infos and then let our super
304 // class DynamicLoader class decide if we should stop or not (based on global
305 // preference).
306 bool DynamicLoaderMacOSXDYLD::NotifyBreakpointHit(
307     void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
308     lldb::user_id_t break_loc_id) {
309   // Let the event know that the images have changed
310   // DYLD passes three arguments to the notification breakpoint.
311   // Arg1: enum dyld_image_mode mode - 0 = adding, 1 = removing Arg2: uint32_t
312   // infoCount        - Number of shared libraries added Arg3: dyld_image_info
313   // info[]    - Array of structs of the form:
314   //                                     const struct mach_header
315   //                                     *imageLoadAddress
316   //                                     const char               *imageFilePath
317   //                                     uintptr_t imageFileModDate (a time_t)
318 
319   DynamicLoaderMacOSXDYLD *dyld_instance = (DynamicLoaderMacOSXDYLD *)baton;
320 
321   // First step is to see if we've already initialized the all image infos.  If
322   // we haven't then this function will do so and return true.  In the course
323   // of initializing the all_image_infos it will read the complete current
324   // state, so we don't need to figure out what has changed from the data
325   // passed in to us.
326 
327   ExecutionContext exe_ctx(context->exe_ctx_ref);
328   Process *process = exe_ctx.GetProcessPtr();
329 
330   // This is a sanity check just in case this dyld_instance is an old dyld
331   // plugin's breakpoint still lying around.
332   if (process != dyld_instance->m_process)
333     return false;
334 
335   if (dyld_instance->InitializeFromAllImageInfos())
336     return dyld_instance->GetStopWhenImagesChange();
337 
338   const lldb::ABISP &abi = process->GetABI();
339   if (abi) {
340     // Build up the value array to store the three arguments given above, then
341     // get the values from the ABI:
342 
343     ClangASTContext *clang_ast_context =
344         process->GetTarget().GetScratchClangASTContext();
345     ValueList argument_values;
346     Value input_value;
347 
348     CompilerType clang_void_ptr_type =
349         clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
350     CompilerType clang_uint32_type =
351         clang_ast_context->GetBuiltinTypeForEncodingAndBitSize(
352             lldb::eEncodingUint, 32);
353     input_value.SetValueType(Value::eValueTypeScalar);
354     input_value.SetCompilerType(clang_uint32_type);
355     //        input_value.SetContext (Value::eContextTypeClangType,
356     //        clang_uint32_type);
357     argument_values.PushValue(input_value);
358     argument_values.PushValue(input_value);
359     input_value.SetCompilerType(clang_void_ptr_type);
360     //        input_value.SetContext (Value::eContextTypeClangType,
361     //        clang_void_ptr_type);
362     argument_values.PushValue(input_value);
363 
364     if (abi->GetArgumentValues(exe_ctx.GetThreadRef(), argument_values)) {
365       uint32_t dyld_mode =
366           argument_values.GetValueAtIndex(0)->GetScalar().UInt(-1);
367       if (dyld_mode != static_cast<uint32_t>(-1)) {
368         // Okay the mode was right, now get the number of elements, and the
369         // array of new elements...
370         uint32_t image_infos_count =
371             argument_values.GetValueAtIndex(1)->GetScalar().UInt(-1);
372         if (image_infos_count != static_cast<uint32_t>(-1)) {
373           // Got the number added, now go through the array of added elements,
374           // putting out the mach header address, and adding the image. Note,
375           // I'm not putting in logging here, since the AddModules &
376           // RemoveModules functions do all the logging internally.
377 
378           lldb::addr_t image_infos_addr =
379               argument_values.GetValueAtIndex(2)->GetScalar().ULongLong();
380           if (dyld_mode == 0) {
381             // This is add:
382             dyld_instance->AddModulesUsingImageInfosAddress(image_infos_addr,
383                                                             image_infos_count);
384           } else {
385             // This is remove:
386             dyld_instance->RemoveModulesUsingImageInfosAddress(
387                 image_infos_addr, image_infos_count);
388           }
389         }
390       }
391     }
392   } else {
393     process->GetTarget().GetDebugger().GetAsyncErrorStream()->Printf(
394         "No ABI plugin located for triple %s -- shared libraries will not be "
395         "registered!\n",
396         process->GetTarget().GetArchitecture().GetTriple().getTriple().c_str());
397   }
398 
399   // Return true to stop the target, false to just let the target run
400   return dyld_instance->GetStopWhenImagesChange();
401 }
402 
403 bool DynamicLoaderMacOSXDYLD::ReadAllImageInfosStructure() {
404   std::lock_guard<std::recursive_mutex> guard(m_mutex);
405 
406   // the all image infos is already valid for this process stop ID
407   if (m_process->GetStopID() == m_dyld_all_image_infos_stop_id)
408     return true;
409 
410   m_dyld_all_image_infos.Clear();
411   if (m_dyld_all_image_infos_addr != LLDB_INVALID_ADDRESS) {
412     ByteOrder byte_order =
413         m_process->GetTarget().GetArchitecture().GetByteOrder();
414     uint32_t addr_size =
415         m_process->GetTarget().GetArchitecture().GetAddressByteSize();
416 
417     uint8_t buf[256];
418     DataExtractor data(buf, sizeof(buf), byte_order, addr_size);
419     lldb::offset_t offset = 0;
420 
421     const size_t count_v2 = sizeof(uint32_t) + // version
422                             sizeof(uint32_t) + // infoArrayCount
423                             addr_size +        // infoArray
424                             addr_size +        // notification
425                             addr_size + // processDetachedFromSharedRegion +
426                                         // libSystemInitialized + pad
427                             addr_size;  // dyldImageLoadAddress
428     const size_t count_v11 = count_v2 + addr_size +  // jitInfo
429                              addr_size +             // dyldVersion
430                              addr_size +             // errorMessage
431                              addr_size +             // terminationFlags
432                              addr_size +             // coreSymbolicationShmPage
433                              addr_size +             // systemOrderFlag
434                              addr_size +             // uuidArrayCount
435                              addr_size +             // uuidArray
436                              addr_size +             // dyldAllImageInfosAddress
437                              addr_size +             // initialImageCount
438                              addr_size +             // errorKind
439                              addr_size +             // errorClientOfDylibPath
440                              addr_size +             // errorTargetDylibPath
441                              addr_size;              // errorSymbol
442     const size_t count_v13 = count_v11 + addr_size + // sharedCacheSlide
443                              sizeof(uuid_t);         // sharedCacheUUID
444     UNUSED_IF_ASSERT_DISABLED(count_v13);
445     assert(sizeof(buf) >= count_v13);
446 
447     Status error;
448     if (m_process->ReadMemory(m_dyld_all_image_infos_addr, buf, 4, error) ==
449         4) {
450       m_dyld_all_image_infos.version = data.GetU32(&offset);
451       // If anything in the high byte is set, we probably got the byte order
452       // incorrect (the process might not have it set correctly yet due to
453       // attaching to a program without a specified file).
454       if (m_dyld_all_image_infos.version & 0xff000000) {
455         // We have guessed the wrong byte order. Swap it and try reading the
456         // version again.
457         if (byte_order == eByteOrderLittle)
458           byte_order = eByteOrderBig;
459         else
460           byte_order = eByteOrderLittle;
461 
462         data.SetByteOrder(byte_order);
463         offset = 0;
464         m_dyld_all_image_infos.version = data.GetU32(&offset);
465       }
466     } else {
467       return false;
468     }
469 
470     const size_t count =
471         (m_dyld_all_image_infos.version >= 11) ? count_v11 : count_v2;
472 
473     const size_t bytes_read =
474         m_process->ReadMemory(m_dyld_all_image_infos_addr, buf, count, error);
475     if (bytes_read == count) {
476       offset = 0;
477       m_dyld_all_image_infos.version = data.GetU32(&offset);
478       m_dyld_all_image_infos.dylib_info_count = data.GetU32(&offset);
479       m_dyld_all_image_infos.dylib_info_addr = data.GetPointer(&offset);
480       m_dyld_all_image_infos.notification = data.GetPointer(&offset);
481       m_dyld_all_image_infos.processDetachedFromSharedRegion =
482           data.GetU8(&offset);
483       m_dyld_all_image_infos.libSystemInitialized = data.GetU8(&offset);
484       // Adjust for padding.
485       offset += addr_size - 2;
486       m_dyld_all_image_infos.dyldImageLoadAddress = data.GetPointer(&offset);
487       if (m_dyld_all_image_infos.version >= 11) {
488         offset += addr_size * 8;
489         uint64_t dyld_all_image_infos_addr = data.GetPointer(&offset);
490 
491         // When we started, we were given the actual address of the
492         // all_image_infos struct (probably via TASK_DYLD_INFO) in memory -
493         // this address is stored in m_dyld_all_image_infos_addr and is the
494         // most accurate address we have.
495 
496         // We read the dyld_all_image_infos struct from memory; it contains its
497         // own address. If the address in the struct does not match the actual
498         // address, the dyld we're looking at has been loaded at a different
499         // location (slid) from where it intended to load.  The addresses in
500         // the dyld_all_image_infos struct are the original, non-slid
501         // addresses, and need to be adjusted.  Most importantly the address of
502         // dyld and the notification address need to be adjusted.
503 
504         if (dyld_all_image_infos_addr != m_dyld_all_image_infos_addr) {
505           uint64_t image_infos_offset =
506               dyld_all_image_infos_addr -
507               m_dyld_all_image_infos.dyldImageLoadAddress;
508           uint64_t notification_offset =
509               m_dyld_all_image_infos.notification -
510               m_dyld_all_image_infos.dyldImageLoadAddress;
511           m_dyld_all_image_infos.dyldImageLoadAddress =
512               m_dyld_all_image_infos_addr - image_infos_offset;
513           m_dyld_all_image_infos.notification =
514               m_dyld_all_image_infos.dyldImageLoadAddress + notification_offset;
515         }
516       }
517       m_dyld_all_image_infos_stop_id = m_process->GetStopID();
518       return true;
519     }
520   }
521   return false;
522 }
523 
524 bool DynamicLoaderMacOSXDYLD::AddModulesUsingImageInfosAddress(
525     lldb::addr_t image_infos_addr, uint32_t image_infos_count) {
526   ImageInfo::collection image_infos;
527   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
528   if (log)
529     log->Printf("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   if (log)
585     log->Printf("Removing %d modules.", image_infos_count);
586 
587   ModuleList unloaded_module_list;
588   for (uint32_t idx = 0; idx < image_infos.size(); ++idx) {
589     if (log) {
590       log->Printf("Removing module at address=0x%16.16" PRIx64 ".",
591                   image_infos[idx].address);
592       image_infos[idx].PutToLog(log);
593     }
594 
595     // Remove this image_infos from the m_all_image_infos.  We do the
596     // comparison by address rather than by file spec because we can have many
597     // modules with the same "file spec" in the case that they are modules
598     // loaded from memory.
599     //
600     // Also copy over the uuid from the old entry to the removed entry so we
601     // can use it to lookup the module in the module list.
602 
603     ImageInfo::collection::iterator pos, end = m_dyld_image_infos.end();
604     for (pos = m_dyld_image_infos.begin(); pos != end; pos++) {
605       if (image_infos[idx].address == (*pos).address) {
606         image_infos[idx].uuid = (*pos).uuid;
607 
608         // Add the module from this image_info to the "unloaded_module_list".
609         // We'll remove them all at one go later on.
610 
611         ModuleSP unload_image_module_sp(
612             FindTargetModuleForImageInfo(image_infos[idx], false, nullptr));
613         if (unload_image_module_sp.get()) {
614           // When we unload, be sure to use the image info from the old list,
615           // since that has sections correctly filled in.
616           UnloadModuleSections(unload_image_module_sp.get(), *pos);
617           unloaded_module_list.AppendIfNeeded(unload_image_module_sp);
618         } else {
619           if (log) {
620             log->Printf("Could not find module for unloading info entry:");
621             image_infos[idx].PutToLog(log);
622           }
623         }
624 
625         // Then remove it from the m_dyld_image_infos:
626 
627         m_dyld_image_infos.erase(pos);
628         break;
629       }
630     }
631 
632     if (pos == end) {
633       if (log) {
634         log->Printf("Could not find image_info entry for unloading image:");
635         image_infos[idx].PutToLog(log);
636       }
637     }
638   }
639   if (unloaded_module_list.GetSize() > 0) {
640     if (log) {
641       log->PutCString("Unloaded:");
642       unloaded_module_list.LogUUIDAndPaths(
643           log, "DynamicLoaderMacOSXDYLD::ModulesDidUnload");
644     }
645     m_process->GetTarget().GetImages().Remove(unloaded_module_list);
646   }
647   m_dyld_image_infos_stop_id = m_process->GetStopID();
648   return true;
649 }
650 
651 bool DynamicLoaderMacOSXDYLD::ReadImageInfos(
652     lldb::addr_t image_infos_addr, uint32_t image_infos_count,
653     ImageInfo::collection &image_infos) {
654   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
655   const ByteOrder endian = GetByteOrderFromMagic(m_dyld.header.magic);
656   const uint32_t addr_size = m_dyld.GetAddressByteSize();
657 
658   image_infos.resize(image_infos_count);
659   const size_t count = image_infos.size() * 3 * addr_size;
660   DataBufferHeap info_data(count, 0);
661   Status error;
662   const size_t bytes_read = m_process->ReadMemory(
663       image_infos_addr, info_data.GetBytes(), info_data.GetByteSize(), error);
664   if (bytes_read == count) {
665     lldb::offset_t info_data_offset = 0;
666     DataExtractor info_data_ref(info_data.GetBytes(), info_data.GetByteSize(),
667                                 endian, addr_size);
668     for (size_t i = 0;
669          i < image_infos.size() && info_data_ref.ValidOffset(info_data_offset);
670          i++) {
671       image_infos[i].address = info_data_ref.GetPointer(&info_data_offset);
672       lldb::addr_t path_addr = info_data_ref.GetPointer(&info_data_offset);
673       image_infos[i].mod_date = info_data_ref.GetPointer(&info_data_offset);
674 
675       char raw_path[PATH_MAX];
676       m_process->ReadCStringFromMemory(path_addr, raw_path, sizeof(raw_path),
677                                        error);
678       // don't resolve the path
679       if (error.Success()) {
680         image_infos[i].file_spec.SetFile(raw_path, FileSpec::Style::native);
681       }
682     }
683     return true;
684   } else {
685     return false;
686   }
687 }
688 
689 // If we have found where the "_dyld_all_image_infos" lives in memory, read the
690 // current info from it, and then update all image load addresses (or lack
691 // thereof).  Only do this if this is the first time we're reading the dyld
692 // infos.  Return true if we actually read anything, and false otherwise.
693 bool DynamicLoaderMacOSXDYLD::InitializeFromAllImageInfos() {
694   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
695 
696   std::lock_guard<std::recursive_mutex> guard(m_mutex);
697   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
698   if (m_process->GetStopID() == m_dyld_image_infos_stop_id ||
699       m_dyld_image_infos.size() != 0)
700     return false;
701 
702   if (ReadAllImageInfosStructure()) {
703     // Nothing to load or unload?
704     if (m_dyld_all_image_infos.dylib_info_count == 0)
705       return true;
706 
707     if (m_dyld_all_image_infos.dylib_info_addr == 0) {
708       // DYLD is updating the images now.  So we should say we have no images,
709       // and then we'll
710       // figure it out when we hit the added breakpoint.
711       return false;
712     } else {
713       if (!AddModulesUsingImageInfosAddress(
714               m_dyld_all_image_infos.dylib_info_addr,
715               m_dyld_all_image_infos.dylib_info_count)) {
716         DEBUG_PRINTF("%s", "unable to read all data for all_dylib_infos.");
717         m_dyld_image_infos.clear();
718       }
719     }
720 
721     // Now we have one more bit of business.  If there is a library left in the
722     // images for our target that doesn't have a load address, then it must be
723     // something that we were expecting to load (for instance we read a load
724     // command for it) but it didn't in fact load - probably because
725     // DYLD_*_PATH pointed to an equivalent version.  We don't want it to stay
726     // in the target's module list or it will confuse us, so unload it here.
727     Target &target = m_process->GetTarget();
728     const ModuleList &target_modules = target.GetImages();
729     ModuleList not_loaded_modules;
730     std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
731 
732     size_t num_modules = target_modules.GetSize();
733     for (size_t i = 0; i < num_modules; i++) {
734       ModuleSP module_sp = target_modules.GetModuleAtIndexUnlocked(i);
735       if (!module_sp->IsLoadedInTarget(&target)) {
736         if (log) {
737           StreamString s;
738           module_sp->GetDescription(&s);
739           log->Printf("Unloading pre-run module: %s.", s.GetData());
740         }
741         not_loaded_modules.Append(module_sp);
742       }
743     }
744 
745     if (not_loaded_modules.GetSize() != 0) {
746       target.GetImages().Remove(not_loaded_modules);
747     }
748 
749     return true;
750   } else
751     return false;
752 }
753 
754 // Read a mach_header at ADDR into HEADER, and also fill in the load command
755 // data into LOAD_COMMAND_DATA if it is non-NULL.
756 //
757 // Returns true if we succeed, false if we fail for any reason.
758 bool DynamicLoaderMacOSXDYLD::ReadMachHeader(lldb::addr_t addr,
759                                              llvm::MachO::mach_header *header,
760                                              DataExtractor *load_command_data) {
761   DataBufferHeap header_bytes(sizeof(llvm::MachO::mach_header), 0);
762   Status error;
763   size_t bytes_read = m_process->ReadMemory(addr, header_bytes.GetBytes(),
764                                             header_bytes.GetByteSize(), error);
765   if (bytes_read == sizeof(llvm::MachO::mach_header)) {
766     lldb::offset_t offset = 0;
767     ::memset(header, 0, sizeof(llvm::MachO::mach_header));
768 
769     // Get the magic byte unswapped so we can figure out what we are dealing
770     // with
771     DataExtractor data(header_bytes.GetBytes(), header_bytes.GetByteSize(),
772                        endian::InlHostByteOrder(), 4);
773     header->magic = data.GetU32(&offset);
774     lldb::addr_t load_cmd_addr = addr;
775     data.SetByteOrder(
776         DynamicLoaderMacOSXDYLD::GetByteOrderFromMagic(header->magic));
777     switch (header->magic) {
778     case llvm::MachO::MH_MAGIC:
779     case llvm::MachO::MH_CIGAM:
780       data.SetAddressByteSize(4);
781       load_cmd_addr += sizeof(llvm::MachO::mach_header);
782       break;
783 
784     case llvm::MachO::MH_MAGIC_64:
785     case llvm::MachO::MH_CIGAM_64:
786       data.SetAddressByteSize(8);
787       load_cmd_addr += sizeof(llvm::MachO::mach_header_64);
788       break;
789 
790     default:
791       return false;
792     }
793 
794     // Read the rest of dyld's mach header
795     if (data.GetU32(&offset, &header->cputype,
796                     (sizeof(llvm::MachO::mach_header) / sizeof(uint32_t)) -
797                         1)) {
798       if (load_command_data == nullptr)
799         return true; // We were able to read the mach_header and weren't asked
800                      // to read the load command bytes
801 
802       DataBufferSP load_cmd_data_sp(new DataBufferHeap(header->sizeofcmds, 0));
803 
804       size_t load_cmd_bytes_read =
805           m_process->ReadMemory(load_cmd_addr, load_cmd_data_sp->GetBytes(),
806                                 load_cmd_data_sp->GetByteSize(), error);
807 
808       if (load_cmd_bytes_read == header->sizeofcmds) {
809         // Set the load command data and also set the correct endian swap
810         // settings and the correct address size
811         load_command_data->SetData(load_cmd_data_sp, 0, header->sizeofcmds);
812         load_command_data->SetByteOrder(data.GetByteOrder());
813         load_command_data->SetAddressByteSize(data.GetAddressByteSize());
814         return true; // We successfully read the mach_header and the load
815                      // command data
816       }
817 
818       return false; // We weren't able to read the load command data
819     }
820   }
821   return false; // We failed the read the mach_header
822 }
823 
824 // Parse the load commands for an image
825 uint32_t DynamicLoaderMacOSXDYLD::ParseLoadCommands(const DataExtractor &data,
826                                                     ImageInfo &dylib_info,
827                                                     FileSpec *lc_id_dylinker) {
828   lldb::offset_t offset = 0;
829   uint32_t cmd_idx;
830   Segment segment;
831   dylib_info.Clear(true);
832 
833   for (cmd_idx = 0; cmd_idx < dylib_info.header.ncmds; cmd_idx++) {
834     // Clear out any load command specific data from DYLIB_INFO since we are
835     // about to read it.
836 
837     if (data.ValidOffsetForDataOfSize(offset,
838                                       sizeof(llvm::MachO::load_command))) {
839       llvm::MachO::load_command load_cmd;
840       lldb::offset_t load_cmd_offset = offset;
841       load_cmd.cmd = data.GetU32(&offset);
842       load_cmd.cmdsize = data.GetU32(&offset);
843       switch (load_cmd.cmd) {
844       case llvm::MachO::LC_SEGMENT: {
845         segment.name.SetTrimmedCStringWithLength(
846             (const char *)data.GetData(&offset, 16), 16);
847         // We are putting 4 uint32_t values 4 uint64_t values so we have to use
848         // multiple 32 bit gets below.
849         segment.vmaddr = data.GetU32(&offset);
850         segment.vmsize = data.GetU32(&offset);
851         segment.fileoff = data.GetU32(&offset);
852         segment.filesize = data.GetU32(&offset);
853         // Extract maxprot, initprot, nsects and flags all at once
854         data.GetU32(&offset, &segment.maxprot, 4);
855         dylib_info.segments.push_back(segment);
856       } break;
857 
858       case llvm::MachO::LC_SEGMENT_64: {
859         segment.name.SetTrimmedCStringWithLength(
860             (const char *)data.GetData(&offset, 16), 16);
861         // Extract vmaddr, vmsize, fileoff, and filesize all at once
862         data.GetU64(&offset, &segment.vmaddr, 4);
863         // Extract maxprot, initprot, nsects and flags all at once
864         data.GetU32(&offset, &segment.maxprot, 4);
865         dylib_info.segments.push_back(segment);
866       } break;
867 
868       case llvm::MachO::LC_ID_DYLINKER:
869         if (lc_id_dylinker) {
870           const lldb::offset_t name_offset =
871               load_cmd_offset + data.GetU32(&offset);
872           const char *path = data.PeekCStr(name_offset);
873           lc_id_dylinker->SetFile(path, FileSpec::Style::native);
874           FileSystem::Instance().Resolve(*lc_id_dylinker);
875         }
876         break;
877 
878       case llvm::MachO::LC_UUID:
879         dylib_info.uuid = UUID::fromOptionalData(data.GetData(&offset, 16), 16);
880         break;
881 
882       default:
883         break;
884       }
885       // Set offset to be the beginning of the next load command.
886       offset = load_cmd_offset + load_cmd.cmdsize;
887     }
888   }
889 
890   // All sections listed in the dyld image info structure will all either be
891   // fixed up already, or they will all be off by a single slide amount that is
892   // determined by finding the first segment that is at file offset zero which
893   // also has bytes (a file size that is greater than zero) in the object file.
894 
895   // Determine the slide amount (if any)
896   const size_t num_sections = dylib_info.segments.size();
897   for (size_t i = 0; i < num_sections; ++i) {
898     // Iterate through the object file sections to find the first section that
899     // starts of file offset zero and that has bytes in the file...
900     if ((dylib_info.segments[i].fileoff == 0 &&
901          dylib_info.segments[i].filesize > 0) ||
902         (dylib_info.segments[i].name == "__TEXT")) {
903       dylib_info.slide = dylib_info.address - dylib_info.segments[i].vmaddr;
904       // We have found the slide amount, so we can exit this for loop.
905       break;
906     }
907   }
908   return cmd_idx;
909 }
910 
911 // Read the mach_header and load commands for each image that the
912 // _dyld_all_image_infos structure points to and cache the results.
913 
914 void DynamicLoaderMacOSXDYLD::UpdateImageInfosHeaderAndLoadCommands(
915     ImageInfo::collection &image_infos, uint32_t infos_count,
916     bool update_executable) {
917   uint32_t exe_idx = UINT32_MAX;
918   // Read any UUID values that we can get
919   for (uint32_t i = 0; i < infos_count; i++) {
920     if (!image_infos[i].UUIDValid()) {
921       DataExtractor data; // Load command data
922       if (!ReadMachHeader(image_infos[i].address, &image_infos[i].header,
923                           &data))
924         continue;
925 
926       ParseLoadCommands(data, image_infos[i], nullptr);
927 
928       if (image_infos[i].header.filetype == llvm::MachO::MH_EXECUTE)
929         exe_idx = i;
930     }
931   }
932 
933   Target &target = m_process->GetTarget();
934 
935   if (exe_idx < image_infos.size()) {
936     const bool can_create = true;
937     ModuleSP exe_module_sp(FindTargetModuleForImageInfo(image_infos[exe_idx],
938                                                         can_create, nullptr));
939 
940     if (exe_module_sp) {
941       UpdateImageLoadAddress(exe_module_sp.get(), image_infos[exe_idx]);
942 
943       if (exe_module_sp.get() != target.GetExecutableModulePointer()) {
944         // Don't load dependent images since we are in dyld where we will know
945         // and find out about all images that are loaded. Also when setting the
946         // executable module, it will clear the targets module list, and if we
947         // have an in memory dyld module, it will get removed from the list so
948         // we will need to add it back after setting the executable module, so
949         // we first try and see if we already have a weak pointer to the dyld
950         // module, make it into a shared pointer, then add the executable, then
951         // re-add it back to make sure it is always in the list.
952         ModuleSP dyld_module_sp(GetDYLDModule());
953 
954         m_process->GetTarget().SetExecutableModule(exe_module_sp,
955                                                    eLoadDependentsNo);
956 
957         if (dyld_module_sp) {
958           if (target.GetImages().AppendIfNeeded(dyld_module_sp)) {
959             std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
960 
961             // Also add it to the section list.
962             UpdateImageLoadAddress(dyld_module_sp.get(), m_dyld);
963           }
964         }
965       }
966     }
967   }
968 }
969 
970 // Dump the _dyld_all_image_infos members and all current image infos that we
971 // have parsed to the file handle provided.
972 void DynamicLoaderMacOSXDYLD::PutToLog(Log *log) const {
973   if (log == nullptr)
974     return;
975 
976   std::lock_guard<std::recursive_mutex> guard(m_mutex);
977   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
978   log->Printf(
979       "dyld_all_image_infos = { version=%d, count=%d, addr=0x%8.8" PRIx64
980       ", notify=0x%8.8" PRIx64 " }",
981       m_dyld_all_image_infos.version, 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