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