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   LLDB_LOGF(log, "Adding %d modules.\n", image_infos_count);
529 
530   std::lock_guard<std::recursive_mutex> guard(m_mutex);
531   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
532   if (m_process->GetStopID() == m_dyld_image_infos_stop_id)
533     return true;
534 
535   StructuredData::ObjectSP image_infos_json_sp =
536       m_process->GetLoadedDynamicLibrariesInfos(image_infos_addr,
537                                                 image_infos_count);
538   if (image_infos_json_sp.get() && image_infos_json_sp->GetAsDictionary() &&
539       image_infos_json_sp->GetAsDictionary()->HasKey("images") &&
540       image_infos_json_sp->GetAsDictionary()
541           ->GetValueForKey("images")
542           ->GetAsArray() &&
543       image_infos_json_sp->GetAsDictionary()
544               ->GetValueForKey("images")
545               ->GetAsArray()
546               ->GetSize() == image_infos_count) {
547     bool return_value = false;
548     if (JSONImageInformationIntoImageInfo(image_infos_json_sp, image_infos)) {
549       UpdateSpecialBinariesFromNewImageInfos(image_infos);
550       return_value = AddModulesUsingImageInfos(image_infos);
551     }
552     m_dyld_image_infos_stop_id = m_process->GetStopID();
553     return return_value;
554   }
555 
556   if (!ReadImageInfos(image_infos_addr, image_infos_count, image_infos))
557     return false;
558 
559   UpdateImageInfosHeaderAndLoadCommands(image_infos, image_infos_count, false);
560   bool return_value = AddModulesUsingImageInfos(image_infos);
561   m_dyld_image_infos_stop_id = m_process->GetStopID();
562   return return_value;
563 }
564 
565 bool DynamicLoaderMacOSXDYLD::RemoveModulesUsingImageInfosAddress(
566     lldb::addr_t image_infos_addr, uint32_t image_infos_count) {
567   ImageInfo::collection image_infos;
568   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
569 
570   std::lock_guard<std::recursive_mutex> guard(m_mutex);
571   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
572   if (m_process->GetStopID() == m_dyld_image_infos_stop_id)
573     return true;
574 
575   // First read in the image_infos for the removed modules, and their headers &
576   // load commands.
577   if (!ReadImageInfos(image_infos_addr, image_infos_count, image_infos)) {
578     if (log)
579       log->PutCString("Failed reading image infos array.");
580     return false;
581   }
582 
583   LLDB_LOGF(log, "Removing %d modules.", image_infos_count);
584 
585   ModuleList unloaded_module_list;
586   for (uint32_t idx = 0; idx < image_infos.size(); ++idx) {
587     if (log) {
588       LLDB_LOGF(log, "Removing module at address=0x%16.16" PRIx64 ".",
589                 image_infos[idx].address);
590       image_infos[idx].PutToLog(log);
591     }
592 
593     // Remove this image_infos from the m_all_image_infos.  We do the
594     // comparison by address rather than by file spec because we can have many
595     // modules with the same "file spec" in the case that they are modules
596     // loaded from memory.
597     //
598     // Also copy over the uuid from the old entry to the removed entry so we
599     // can use it to lookup the module in the module list.
600 
601     ImageInfo::collection::iterator pos, end = m_dyld_image_infos.end();
602     for (pos = m_dyld_image_infos.begin(); pos != end; pos++) {
603       if (image_infos[idx].address == (*pos).address) {
604         image_infos[idx].uuid = (*pos).uuid;
605 
606         // Add the module from this image_info to the "unloaded_module_list".
607         // We'll remove them all at one go later on.
608 
609         ModuleSP unload_image_module_sp(
610             FindTargetModuleForImageInfo(image_infos[idx], false, nullptr));
611         if (unload_image_module_sp.get()) {
612           // When we unload, be sure to use the image info from the old list,
613           // since that has sections correctly filled in.
614           UnloadModuleSections(unload_image_module_sp.get(), *pos);
615           unloaded_module_list.AppendIfNeeded(unload_image_module_sp);
616         } else {
617           if (log) {
618             LLDB_LOGF(log, "Could not find module for unloading info entry:");
619             image_infos[idx].PutToLog(log);
620           }
621         }
622 
623         // Then remove it from the m_dyld_image_infos:
624 
625         m_dyld_image_infos.erase(pos);
626         break;
627       }
628     }
629 
630     if (pos == end) {
631       if (log) {
632         LLDB_LOGF(log, "Could not find image_info entry for unloading image:");
633         image_infos[idx].PutToLog(log);
634       }
635     }
636   }
637   if (unloaded_module_list.GetSize() > 0) {
638     if (log) {
639       log->PutCString("Unloaded:");
640       unloaded_module_list.LogUUIDAndPaths(
641           log, "DynamicLoaderMacOSXDYLD::ModulesDidUnload");
642     }
643     m_process->GetTarget().GetImages().Remove(unloaded_module_list);
644   }
645   m_dyld_image_infos_stop_id = m_process->GetStopID();
646   return true;
647 }
648 
649 bool DynamicLoaderMacOSXDYLD::ReadImageInfos(
650     lldb::addr_t image_infos_addr, uint32_t image_infos_count,
651     ImageInfo::collection &image_infos) {
652   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
653   const ByteOrder endian = GetByteOrderFromMagic(m_dyld.header.magic);
654   const uint32_t addr_size = m_dyld.GetAddressByteSize();
655 
656   image_infos.resize(image_infos_count);
657   const size_t count = image_infos.size() * 3 * addr_size;
658   DataBufferHeap info_data(count, 0);
659   Status error;
660   const size_t bytes_read = m_process->ReadMemory(
661       image_infos_addr, info_data.GetBytes(), info_data.GetByteSize(), error);
662   if (bytes_read == count) {
663     lldb::offset_t info_data_offset = 0;
664     DataExtractor info_data_ref(info_data.GetBytes(), info_data.GetByteSize(),
665                                 endian, addr_size);
666     for (size_t i = 0;
667          i < image_infos.size() && info_data_ref.ValidOffset(info_data_offset);
668          i++) {
669       image_infos[i].address = info_data_ref.GetPointer(&info_data_offset);
670       lldb::addr_t path_addr = info_data_ref.GetPointer(&info_data_offset);
671       image_infos[i].mod_date = info_data_ref.GetPointer(&info_data_offset);
672 
673       char raw_path[PATH_MAX];
674       m_process->ReadCStringFromMemory(path_addr, raw_path, sizeof(raw_path),
675                                        error);
676       // don't resolve the path
677       if (error.Success()) {
678         image_infos[i].file_spec.SetFile(raw_path, FileSpec::Style::native);
679       }
680     }
681     return true;
682   } else {
683     return false;
684   }
685 }
686 
687 // If we have found where the "_dyld_all_image_infos" lives in memory, read the
688 // current info from it, and then update all image load addresses (or lack
689 // thereof).  Only do this if this is the first time we're reading the dyld
690 // infos.  Return true if we actually read anything, and false otherwise.
691 bool DynamicLoaderMacOSXDYLD::InitializeFromAllImageInfos() {
692   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
693 
694   std::lock_guard<std::recursive_mutex> guard(m_mutex);
695   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
696   if (m_process->GetStopID() == m_dyld_image_infos_stop_id ||
697       m_dyld_image_infos.size() != 0)
698     return false;
699 
700   if (ReadAllImageInfosStructure()) {
701     // Nothing to load or unload?
702     if (m_dyld_all_image_infos.dylib_info_count == 0)
703       return true;
704 
705     if (m_dyld_all_image_infos.dylib_info_addr == 0) {
706       // DYLD is updating the images now.  So we should say we have no images,
707       // and then we'll
708       // figure it out when we hit the added breakpoint.
709       return false;
710     } else {
711       if (!AddModulesUsingImageInfosAddress(
712               m_dyld_all_image_infos.dylib_info_addr,
713               m_dyld_all_image_infos.dylib_info_count)) {
714         DEBUG_PRINTF("%s", "unable to read all data for all_dylib_infos.");
715         m_dyld_image_infos.clear();
716       }
717     }
718 
719     // Now we have one more bit of business.  If there is a library left in the
720     // images for our target that doesn't have a load address, then it must be
721     // something that we were expecting to load (for instance we read a load
722     // command for it) but it didn't in fact load - probably because
723     // DYLD_*_PATH pointed to an equivalent version.  We don't want it to stay
724     // in the target's module list or it will confuse us, so unload it here.
725     Target &target = m_process->GetTarget();
726     const ModuleList &target_modules = target.GetImages();
727     ModuleList not_loaded_modules;
728     std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
729 
730     size_t num_modules = target_modules.GetSize();
731     for (size_t i = 0; i < num_modules; i++) {
732       ModuleSP module_sp = target_modules.GetModuleAtIndexUnlocked(i);
733       if (!module_sp->IsLoadedInTarget(&target)) {
734         if (log) {
735           StreamString s;
736           module_sp->GetDescription(&s);
737           LLDB_LOGF(log, "Unloading pre-run module: %s.", s.GetData());
738         }
739         not_loaded_modules.Append(module_sp);
740       }
741     }
742 
743     if (not_loaded_modules.GetSize() != 0) {
744       target.GetImages().Remove(not_loaded_modules);
745     }
746 
747     return true;
748   } else
749     return false;
750 }
751 
752 // Read a mach_header at ADDR into HEADER, and also fill in the load command
753 // data into LOAD_COMMAND_DATA if it is non-NULL.
754 //
755 // Returns true if we succeed, false if we fail for any reason.
756 bool DynamicLoaderMacOSXDYLD::ReadMachHeader(lldb::addr_t addr,
757                                              llvm::MachO::mach_header *header,
758                                              DataExtractor *load_command_data) {
759   DataBufferHeap header_bytes(sizeof(llvm::MachO::mach_header), 0);
760   Status error;
761   size_t bytes_read = m_process->ReadMemory(addr, header_bytes.GetBytes(),
762                                             header_bytes.GetByteSize(), error);
763   if (bytes_read == sizeof(llvm::MachO::mach_header)) {
764     lldb::offset_t offset = 0;
765     ::memset(header, 0, sizeof(llvm::MachO::mach_header));
766 
767     // Get the magic byte unswapped so we can figure out what we are dealing
768     // with
769     DataExtractor data(header_bytes.GetBytes(), header_bytes.GetByteSize(),
770                        endian::InlHostByteOrder(), 4);
771     header->magic = data.GetU32(&offset);
772     lldb::addr_t load_cmd_addr = addr;
773     data.SetByteOrder(
774         DynamicLoaderMacOSXDYLD::GetByteOrderFromMagic(header->magic));
775     switch (header->magic) {
776     case llvm::MachO::MH_MAGIC:
777     case llvm::MachO::MH_CIGAM:
778       data.SetAddressByteSize(4);
779       load_cmd_addr += sizeof(llvm::MachO::mach_header);
780       break;
781 
782     case llvm::MachO::MH_MAGIC_64:
783     case llvm::MachO::MH_CIGAM_64:
784       data.SetAddressByteSize(8);
785       load_cmd_addr += sizeof(llvm::MachO::mach_header_64);
786       break;
787 
788     default:
789       return false;
790     }
791 
792     // Read the rest of dyld's mach header
793     if (data.GetU32(&offset, &header->cputype,
794                     (sizeof(llvm::MachO::mach_header) / sizeof(uint32_t)) -
795                         1)) {
796       if (load_command_data == nullptr)
797         return true; // We were able to read the mach_header and weren't asked
798                      // to read the load command bytes
799 
800       DataBufferSP load_cmd_data_sp(new DataBufferHeap(header->sizeofcmds, 0));
801 
802       size_t load_cmd_bytes_read =
803           m_process->ReadMemory(load_cmd_addr, load_cmd_data_sp->GetBytes(),
804                                 load_cmd_data_sp->GetByteSize(), error);
805 
806       if (load_cmd_bytes_read == header->sizeofcmds) {
807         // Set the load command data and also set the correct endian swap
808         // settings and the correct address size
809         load_command_data->SetData(load_cmd_data_sp, 0, header->sizeofcmds);
810         load_command_data->SetByteOrder(data.GetByteOrder());
811         load_command_data->SetAddressByteSize(data.GetAddressByteSize());
812         return true; // We successfully read the mach_header and the load
813                      // command data
814       }
815 
816       return false; // We weren't able to read the load command data
817     }
818   }
819   return false; // We failed the read the mach_header
820 }
821 
822 // Parse the load commands for an image
823 uint32_t DynamicLoaderMacOSXDYLD::ParseLoadCommands(const DataExtractor &data,
824                                                     ImageInfo &dylib_info,
825                                                     FileSpec *lc_id_dylinker) {
826   lldb::offset_t offset = 0;
827   uint32_t cmd_idx;
828   Segment segment;
829   dylib_info.Clear(true);
830 
831   for (cmd_idx = 0; cmd_idx < dylib_info.header.ncmds; cmd_idx++) {
832     // Clear out any load command specific data from DYLIB_INFO since we are
833     // about to read it.
834 
835     if (data.ValidOffsetForDataOfSize(offset,
836                                       sizeof(llvm::MachO::load_command))) {
837       llvm::MachO::load_command load_cmd;
838       lldb::offset_t load_cmd_offset = offset;
839       load_cmd.cmd = data.GetU32(&offset);
840       load_cmd.cmdsize = data.GetU32(&offset);
841       switch (load_cmd.cmd) {
842       case llvm::MachO::LC_SEGMENT: {
843         segment.name.SetTrimmedCStringWithLength(
844             (const char *)data.GetData(&offset, 16), 16);
845         // We are putting 4 uint32_t values 4 uint64_t values so we have to use
846         // multiple 32 bit gets below.
847         segment.vmaddr = data.GetU32(&offset);
848         segment.vmsize = data.GetU32(&offset);
849         segment.fileoff = data.GetU32(&offset);
850         segment.filesize = data.GetU32(&offset);
851         // Extract maxprot, initprot, nsects and flags all at once
852         data.GetU32(&offset, &segment.maxprot, 4);
853         dylib_info.segments.push_back(segment);
854       } break;
855 
856       case llvm::MachO::LC_SEGMENT_64: {
857         segment.name.SetTrimmedCStringWithLength(
858             (const char *)data.GetData(&offset, 16), 16);
859         // Extract vmaddr, vmsize, fileoff, and filesize all at once
860         data.GetU64(&offset, &segment.vmaddr, 4);
861         // Extract maxprot, initprot, nsects and flags all at once
862         data.GetU32(&offset, &segment.maxprot, 4);
863         dylib_info.segments.push_back(segment);
864       } break;
865 
866       case llvm::MachO::LC_ID_DYLINKER:
867         if (lc_id_dylinker) {
868           const lldb::offset_t name_offset =
869               load_cmd_offset + data.GetU32(&offset);
870           const char *path = data.PeekCStr(name_offset);
871           lc_id_dylinker->SetFile(path, FileSpec::Style::native);
872           FileSystem::Instance().Resolve(*lc_id_dylinker);
873         }
874         break;
875 
876       case llvm::MachO::LC_UUID:
877         dylib_info.uuid = UUID::fromOptionalData(data.GetData(&offset, 16), 16);
878         break;
879 
880       default:
881         break;
882       }
883       // Set offset to be the beginning of the next load command.
884       offset = load_cmd_offset + load_cmd.cmdsize;
885     }
886   }
887 
888   // All sections listed in the dyld image info structure will all either be
889   // fixed up already, or they will all be off by a single slide amount that is
890   // determined by finding the first segment that is at file offset zero which
891   // also has bytes (a file size that is greater than zero) in the object file.
892 
893   // Determine the slide amount (if any)
894   const size_t num_sections = dylib_info.segments.size();
895   for (size_t i = 0; i < num_sections; ++i) {
896     // Iterate through the object file sections to find the first section that
897     // starts of file offset zero and that has bytes in the file...
898     if ((dylib_info.segments[i].fileoff == 0 &&
899          dylib_info.segments[i].filesize > 0) ||
900         (dylib_info.segments[i].name == "__TEXT")) {
901       dylib_info.slide = dylib_info.address - dylib_info.segments[i].vmaddr;
902       // We have found the slide amount, so we can exit this for loop.
903       break;
904     }
905   }
906   return cmd_idx;
907 }
908 
909 // Read the mach_header and load commands for each image that the
910 // _dyld_all_image_infos structure points to and cache the results.
911 
912 void DynamicLoaderMacOSXDYLD::UpdateImageInfosHeaderAndLoadCommands(
913     ImageInfo::collection &image_infos, uint32_t infos_count,
914     bool update_executable) {
915   uint32_t exe_idx = UINT32_MAX;
916   // Read any UUID values that we can get
917   for (uint32_t i = 0; i < infos_count; i++) {
918     if (!image_infos[i].UUIDValid()) {
919       DataExtractor data; // Load command data
920       if (!ReadMachHeader(image_infos[i].address, &image_infos[i].header,
921                           &data))
922         continue;
923 
924       ParseLoadCommands(data, image_infos[i], nullptr);
925 
926       if (image_infos[i].header.filetype == llvm::MachO::MH_EXECUTE)
927         exe_idx = i;
928     }
929   }
930 
931   Target &target = m_process->GetTarget();
932 
933   if (exe_idx < image_infos.size()) {
934     const bool can_create = true;
935     ModuleSP exe_module_sp(FindTargetModuleForImageInfo(image_infos[exe_idx],
936                                                         can_create, nullptr));
937 
938     if (exe_module_sp) {
939       UpdateImageLoadAddress(exe_module_sp.get(), image_infos[exe_idx]);
940 
941       if (exe_module_sp.get() != target.GetExecutableModulePointer()) {
942         // Don't load dependent images since we are in dyld where we will know
943         // and find out about all images that are loaded. Also when setting the
944         // executable module, it will clear the targets module list, and if we
945         // have an in memory dyld module, it will get removed from the list so
946         // we will need to add it back after setting the executable module, so
947         // we first try and see if we already have a weak pointer to the dyld
948         // module, make it into a shared pointer, then add the executable, then
949         // re-add it back to make sure it is always in the list.
950         ModuleSP dyld_module_sp(GetDYLDModule());
951 
952         m_process->GetTarget().SetExecutableModule(exe_module_sp,
953                                                    eLoadDependentsNo);
954 
955         if (dyld_module_sp) {
956           if (target.GetImages().AppendIfNeeded(dyld_module_sp)) {
957             std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
958 
959             // Also add it to the section list.
960             UpdateImageLoadAddress(dyld_module_sp.get(), m_dyld);
961           }
962         }
963       }
964     }
965   }
966 }
967 
968 // Dump the _dyld_all_image_infos members and all current image infos that we
969 // have parsed to the file handle provided.
970 void DynamicLoaderMacOSXDYLD::PutToLog(Log *log) const {
971   if (log == nullptr)
972     return;
973 
974   std::lock_guard<std::recursive_mutex> guard(m_mutex);
975   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
976   LLDB_LOGF(log,
977             "dyld_all_image_infos = { version=%d, count=%d, addr=0x%8.8" PRIx64
978             ", notify=0x%8.8" PRIx64 " }",
979             m_dyld_all_image_infos.version,
980             m_dyld_all_image_infos.dylib_info_count,
981             (uint64_t)m_dyld_all_image_infos.dylib_info_addr,
982             (uint64_t)m_dyld_all_image_infos.notification);
983   size_t i;
984   const size_t count = m_dyld_image_infos.size();
985   if (count > 0) {
986     log->PutCString("Loaded:");
987     for (i = 0; i < count; i++)
988       m_dyld_image_infos[i].PutToLog(log);
989   }
990 }
991 
992 bool DynamicLoaderMacOSXDYLD::SetNotificationBreakpoint() {
993   DEBUG_PRINTF("DynamicLoaderMacOSXDYLD::%s() process state = %s\n",
994                __FUNCTION__, StateAsCString(m_process->GetState()));
995   if (m_break_id == LLDB_INVALID_BREAK_ID) {
996     if (m_dyld_all_image_infos.notification != LLDB_INVALID_ADDRESS) {
997       Address so_addr;
998       // Set the notification breakpoint and install a breakpoint callback
999       // function that will get called each time the breakpoint gets hit. We
1000       // will use this to track when shared libraries get loaded/unloaded.
1001       bool resolved = m_process->GetTarget().ResolveLoadAddress(
1002           m_dyld_all_image_infos.notification, so_addr);
1003       if (!resolved) {
1004         ModuleSP dyld_module_sp = GetDYLDModule();
1005         if (dyld_module_sp) {
1006           std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
1007 
1008           UpdateImageLoadAddress(dyld_module_sp.get(), m_dyld);
1009           resolved = m_process->GetTarget().ResolveLoadAddress(
1010               m_dyld_all_image_infos.notification, so_addr);
1011         }
1012       }
1013 
1014       if (resolved) {
1015         Breakpoint *dyld_break =
1016             m_process->GetTarget().CreateBreakpoint(so_addr, true, false).get();
1017         dyld_break->SetCallback(DynamicLoaderMacOSXDYLD::NotifyBreakpointHit,
1018                                 this, true);
1019         dyld_break->SetBreakpointKind("shared-library-event");
1020         m_break_id = dyld_break->GetID();
1021       }
1022     }
1023   }
1024   return m_break_id != LLDB_INVALID_BREAK_ID;
1025 }
1026 
1027 Status DynamicLoaderMacOSXDYLD::CanLoadImage() {
1028   Status error;
1029   // In order for us to tell if we can load a shared library we verify that the
1030   // dylib_info_addr isn't zero (which means no shared libraries have been set
1031   // yet, or dyld is currently mucking with the shared library list).
1032   if (ReadAllImageInfosStructure()) {
1033     // TODO: also check the _dyld_global_lock_held variable in
1034     // libSystem.B.dylib?
1035     // TODO: check the malloc lock?
1036     // TODO: check the objective C lock?
1037     if (m_dyld_all_image_infos.dylib_info_addr != 0)
1038       return error; // Success
1039   }
1040 
1041   error.SetErrorString("unsafe to load or unload shared libraries");
1042   return error;
1043 }
1044 
1045 bool DynamicLoaderMacOSXDYLD::GetSharedCacheInformation(
1046     lldb::addr_t &base_address, UUID &uuid, LazyBool &using_shared_cache,
1047     LazyBool &private_shared_cache) {
1048   base_address = LLDB_INVALID_ADDRESS;
1049   uuid.Clear();
1050   using_shared_cache = eLazyBoolCalculate;
1051   private_shared_cache = eLazyBoolCalculate;
1052 
1053   if (m_process) {
1054     addr_t all_image_infos = m_process->GetImageInfoAddress();
1055 
1056     // The address returned by GetImageInfoAddress may be the address of dyld
1057     // (don't want) or it may be the address of the dyld_all_image_infos
1058     // structure (want). The first four bytes will be either the version field
1059     // (all_image_infos) or a Mach-O file magic constant. Version 13 and higher
1060     // of dyld_all_image_infos is required to get the sharedCacheUUID field.
1061 
1062     Status err;
1063     uint32_t version_or_magic =
1064         m_process->ReadUnsignedIntegerFromMemory(all_image_infos, 4, -1, err);
1065     if (version_or_magic != static_cast<uint32_t>(-1) &&
1066         version_or_magic != llvm::MachO::MH_MAGIC &&
1067         version_or_magic != llvm::MachO::MH_CIGAM &&
1068         version_or_magic != llvm::MachO::MH_MAGIC_64 &&
1069         version_or_magic != llvm::MachO::MH_CIGAM_64 &&
1070         version_or_magic >= 13) {
1071       addr_t sharedCacheUUID_address = LLDB_INVALID_ADDRESS;
1072       int wordsize = m_process->GetAddressByteSize();
1073       if (wordsize == 8) {
1074         sharedCacheUUID_address =
1075             all_image_infos + 160; // sharedCacheUUID <mach-o/dyld_images.h>
1076       }
1077       if (wordsize == 4) {
1078         sharedCacheUUID_address =
1079             all_image_infos + 84; // sharedCacheUUID <mach-o/dyld_images.h>
1080       }
1081       if (sharedCacheUUID_address != LLDB_INVALID_ADDRESS) {
1082         uuid_t shared_cache_uuid;
1083         if (m_process->ReadMemory(sharedCacheUUID_address, shared_cache_uuid,
1084                                   sizeof(uuid_t), err) == sizeof(uuid_t)) {
1085           uuid = UUID::fromOptionalData(shared_cache_uuid, 16);
1086           if (uuid.IsValid()) {
1087             using_shared_cache = eLazyBoolYes;
1088           }
1089         }
1090 
1091         if (version_or_magic >= 15) {
1092           // The sharedCacheBaseAddress field is the next one in the
1093           // dyld_all_image_infos struct.
1094           addr_t sharedCacheBaseAddr_address = sharedCacheUUID_address + 16;
1095           Status error;
1096           base_address = m_process->ReadUnsignedIntegerFromMemory(
1097               sharedCacheBaseAddr_address, wordsize, LLDB_INVALID_ADDRESS,
1098               error);
1099           if (error.Fail())
1100             base_address = LLDB_INVALID_ADDRESS;
1101         }
1102 
1103         return true;
1104       }
1105 
1106       //
1107       // add
1108       // NB: sharedCacheBaseAddress is the next field in dyld_all_image_infos
1109       // after
1110       // sharedCacheUUID -- that is, 16 bytes after it, if we wanted to fetch
1111       // it.
1112     }
1113   }
1114   return false;
1115 }
1116 
1117 void DynamicLoaderMacOSXDYLD::Initialize() {
1118   PluginManager::RegisterPlugin(GetPluginNameStatic(),
1119                                 GetPluginDescriptionStatic(), CreateInstance);
1120 }
1121 
1122 void DynamicLoaderMacOSXDYLD::Terminate() {
1123   PluginManager::UnregisterPlugin(CreateInstance);
1124 }
1125 
1126 lldb_private::ConstString DynamicLoaderMacOSXDYLD::GetPluginNameStatic() {
1127   static ConstString g_name("macosx-dyld");
1128   return g_name;
1129 }
1130 
1131 const char *DynamicLoaderMacOSXDYLD::GetPluginDescriptionStatic() {
1132   return "Dynamic loader plug-in that watches for shared library loads/unloads "
1133          "in MacOSX user processes.";
1134 }
1135 
1136 // PluginInterface protocol
1137 lldb_private::ConstString DynamicLoaderMacOSXDYLD::GetPluginName() {
1138   return GetPluginNameStatic();
1139 }
1140 
1141 uint32_t DynamicLoaderMacOSXDYLD::GetPluginVersion() { return 1; }
1142 
1143 uint32_t DynamicLoaderMacOSXDYLD::AddrByteSize() {
1144   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
1145 
1146   switch (m_dyld.header.magic) {
1147   case llvm::MachO::MH_MAGIC:
1148   case llvm::MachO::MH_CIGAM:
1149     return 4;
1150 
1151   case llvm::MachO::MH_MAGIC_64:
1152   case llvm::MachO::MH_CIGAM_64:
1153     return 8;
1154 
1155   default:
1156     break;
1157   }
1158   return 0;
1159 }
1160 
1161 lldb::ByteOrder DynamicLoaderMacOSXDYLD::GetByteOrderFromMagic(uint32_t magic) {
1162   switch (magic) {
1163   case llvm::MachO::MH_MAGIC:
1164   case llvm::MachO::MH_MAGIC_64:
1165     return endian::InlHostByteOrder();
1166 
1167   case llvm::MachO::MH_CIGAM:
1168   case llvm::MachO::MH_CIGAM_64:
1169     if (endian::InlHostByteOrder() == lldb::eByteOrderBig)
1170       return lldb::eByteOrderLittle;
1171     else
1172       return lldb::eByteOrderBig;
1173 
1174   default:
1175     break;
1176   }
1177   return lldb::eByteOrderInvalid;
1178 }
1179