1 //===-- DynamicLoaderMacOSXDYLD.cpp ---------------------------------------===//
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 "DynamicLoaderMacOSXDYLD.h"
10 #include "DynamicLoaderDarwin.h"
11 #include "DynamicLoaderMacOS.h"
12 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
13 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
14 #include "lldb/Breakpoint/StoppointCallbackContext.h"
15 #include "lldb/Core/Debugger.h"
16 #include "lldb/Core/Module.h"
17 #include "lldb/Core/ModuleSpec.h"
18 #include "lldb/Core/PluginManager.h"
19 #include "lldb/Core/Section.h"
20 #include "lldb/Symbol/Function.h"
21 #include "lldb/Symbol/ObjectFile.h"
22 #include "lldb/Target/ABI.h"
23 #include "lldb/Target/RegisterContext.h"
24 #include "lldb/Target/StackFrame.h"
25 #include "lldb/Target/Target.h"
26 #include "lldb/Target/Thread.h"
27 #include "lldb/Target/ThreadPlanRunToAddress.h"
28 #include "lldb/Utility/DataBuffer.h"
29 #include "lldb/Utility/DataBufferHeap.h"
30 #include "lldb/Utility/Log.h"
31 #include "lldb/Utility/State.h"
32 
33 //#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN
34 #ifdef ENABLE_DEBUG_PRINTF
35 #include <cstdio>
36 #define DEBUG_PRINTF(fmt, ...) printf(fmt, ##__VA_ARGS__)
37 #else
38 #define DEBUG_PRINTF(fmt, ...)
39 #endif
40 
41 #ifndef __APPLE__
42 #include "Utility/UuidCompatibility.h"
43 #else
44 #include <uuid/uuid.h>
45 #endif
46 
47 using namespace lldb;
48 using namespace lldb_private;
49 
LLDB_PLUGIN_DEFINE(DynamicLoaderMacOSXDYLD)50 LLDB_PLUGIN_DEFINE(DynamicLoaderMacOSXDYLD)
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 DynamicLoader *DynamicLoaderMacOSXDYLD::CreateInstance(Process *process,
56                                                        bool force) {
57   bool create = force;
58   if (!create) {
59     create = true;
60     Module *exe_module = process->GetTarget().GetExecutableModulePointer();
61     if (exe_module) {
62       ObjectFile *object_file = exe_module->GetObjectFile();
63       if (object_file) {
64         create = (object_file->GetStrata() == ObjectFile::eStrataUser);
65       }
66     }
67 
68     if (create) {
69       const llvm::Triple &triple_ref =
70           process->GetTarget().GetArchitecture().GetTriple();
71       switch (triple_ref.getOS()) {
72       case llvm::Triple::Darwin:
73       case llvm::Triple::MacOSX:
74       case llvm::Triple::IOS:
75       case llvm::Triple::TvOS:
76       case llvm::Triple::WatchOS:
77       // NEED_BRIDGEOS_TRIPLE case llvm::Triple::BridgeOS:
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)) {
88     create = false;
89   }
90 
91   if (create)
92     return new DynamicLoaderMacOSXDYLD(process);
93   return nullptr;
94 }
95 
96 // Constructor
DynamicLoaderMacOSXDYLD(Process * process)97 DynamicLoaderMacOSXDYLD::DynamicLoaderMacOSXDYLD(Process *process)
98     : DynamicLoaderDarwin(process),
99       m_dyld_all_image_infos_addr(LLDB_INVALID_ADDRESS),
100       m_dyld_all_image_infos(), m_dyld_all_image_infos_stop_id(UINT32_MAX),
101       m_break_id(LLDB_INVALID_BREAK_ID), m_mutex(),
102       m_process_image_addr_is_all_images_infos(false) {}
103 
104 // Destructor
~DynamicLoaderMacOSXDYLD()105 DynamicLoaderMacOSXDYLD::~DynamicLoaderMacOSXDYLD() {
106   if (LLDB_BREAK_ID_IS_VALID(m_break_id))
107     m_process->GetTarget().RemoveBreakpointByID(m_break_id);
108 }
109 
ProcessDidExec()110 bool DynamicLoaderMacOSXDYLD::ProcessDidExec() {
111   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
112   bool did_exec = false;
113   if (m_process) {
114     // If we are stopped after an exec, we will have only one thread...
115     if (m_process->GetThreadList().GetSize() == 1) {
116       // We know if a process has exec'ed if our "m_dyld_all_image_infos_addr"
117       // value differs from the Process' image info address. When a process
118       // execs itself it might cause a change if ASLR is enabled.
119       const addr_t shlib_addr = m_process->GetImageInfoAddress();
120       if (m_process_image_addr_is_all_images_infos &&
121           shlib_addr != m_dyld_all_image_infos_addr) {
122         // The image info address from the process is the
123         // 'dyld_all_image_infos' address and it has changed.
124         did_exec = true;
125       } else if (!m_process_image_addr_is_all_images_infos &&
126                  shlib_addr == m_dyld.address) {
127         // The image info address from the process is the mach_header address
128         // for dyld and it has changed.
129         did_exec = true;
130       } else {
131         // ASLR might be disabled and dyld could have ended up in the same
132         // location. We should try and detect if we are stopped at
133         // '_dyld_start'
134         ThreadSP thread_sp(m_process->GetThreadList().GetThreadAtIndex(0));
135         if (thread_sp) {
136           lldb::StackFrameSP frame_sp(thread_sp->GetStackFrameAtIndex(0));
137           if (frame_sp) {
138             const Symbol *symbol =
139                 frame_sp->GetSymbolContext(eSymbolContextSymbol).symbol;
140             if (symbol) {
141               if (symbol->GetName() == "_dyld_start")
142                 did_exec = true;
143             }
144           }
145         }
146       }
147 
148       if (did_exec) {
149         m_libpthread_module_wp.reset();
150         m_pthread_getspecific_addr.Clear();
151       }
152     }
153   }
154   return did_exec;
155 }
156 
157 // Clear out the state of this class.
DoClear()158 void DynamicLoaderMacOSXDYLD::DoClear() {
159   std::lock_guard<std::recursive_mutex> guard(m_mutex);
160 
161   if (LLDB_BREAK_ID_IS_VALID(m_break_id))
162     m_process->GetTarget().RemoveBreakpointByID(m_break_id);
163 
164   m_dyld_all_image_infos_addr = LLDB_INVALID_ADDRESS;
165   m_dyld_all_image_infos.Clear();
166   m_break_id = LLDB_INVALID_BREAK_ID;
167 }
168 
169 // Check if we have found DYLD yet
DidSetNotificationBreakpoint()170 bool DynamicLoaderMacOSXDYLD::DidSetNotificationBreakpoint() {
171   return LLDB_BREAK_ID_IS_VALID(m_break_id);
172 }
173 
ClearNotificationBreakpoint()174 void DynamicLoaderMacOSXDYLD::ClearNotificationBreakpoint() {
175   if (LLDB_BREAK_ID_IS_VALID(m_break_id)) {
176     m_process->GetTarget().RemoveBreakpointByID(m_break_id);
177   }
178 }
179 
180 // Try and figure out where dyld is by first asking the Process if it knows
181 // (which currently calls down in the lldb::Process to get the DYLD info
182 // (available on SnowLeopard only). If that fails, then check in the default
183 // addresses.
DoInitialImageFetch()184 void DynamicLoaderMacOSXDYLD::DoInitialImageFetch() {
185   if (m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS) {
186     // Check the image info addr as it might point to the mach header for dyld,
187     // or it might point to the dyld_all_image_infos struct
188     const addr_t shlib_addr = m_process->GetImageInfoAddress();
189     if (shlib_addr != LLDB_INVALID_ADDRESS) {
190       ByteOrder byte_order =
191           m_process->GetTarget().GetArchitecture().GetByteOrder();
192       uint8_t buf[4];
193       DataExtractor data(buf, sizeof(buf), byte_order, 4);
194       Status error;
195       if (m_process->ReadMemory(shlib_addr, buf, 4, error) == 4) {
196         lldb::offset_t offset = 0;
197         uint32_t magic = data.GetU32(&offset);
198         switch (magic) {
199         case llvm::MachO::MH_MAGIC:
200         case llvm::MachO::MH_MAGIC_64:
201         case llvm::MachO::MH_CIGAM:
202         case llvm::MachO::MH_CIGAM_64:
203           m_process_image_addr_is_all_images_infos = false;
204           ReadDYLDInfoFromMemoryAndSetNotificationCallback(shlib_addr);
205           return;
206 
207         default:
208           break;
209         }
210       }
211       // Maybe it points to the all image infos?
212       m_dyld_all_image_infos_addr = shlib_addr;
213       m_process_image_addr_is_all_images_infos = true;
214     }
215   }
216 
217   if (m_dyld_all_image_infos_addr != LLDB_INVALID_ADDRESS) {
218     if (ReadAllImageInfosStructure()) {
219       if (m_dyld_all_image_infos.dyldImageLoadAddress != LLDB_INVALID_ADDRESS)
220         ReadDYLDInfoFromMemoryAndSetNotificationCallback(
221             m_dyld_all_image_infos.dyldImageLoadAddress);
222       else
223         ReadDYLDInfoFromMemoryAndSetNotificationCallback(
224             m_dyld_all_image_infos_addr & 0xfffffffffff00000ull);
225       return;
226     }
227   }
228 
229   // Check some default values
230   Module *executable = m_process->GetTarget().GetExecutableModulePointer();
231 
232   if (executable) {
233     const ArchSpec &exe_arch = executable->GetArchitecture();
234     if (exe_arch.GetAddressByteSize() == 8) {
235       ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x7fff5fc00000ull);
236     } else if (exe_arch.GetMachine() == llvm::Triple::arm ||
237                exe_arch.GetMachine() == llvm::Triple::thumb ||
238                exe_arch.GetMachine() == llvm::Triple::aarch64 ||
239                exe_arch.GetMachine() == llvm::Triple::aarch64_32) {
240       ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x2fe00000);
241     } else {
242       ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x8fe00000);
243     }
244   }
245   return;
246 }
247 
248 // Assume that dyld is in memory at ADDR and try to parse it's load commands
ReadDYLDInfoFromMemoryAndSetNotificationCallback(lldb::addr_t addr)249 bool DynamicLoaderMacOSXDYLD::ReadDYLDInfoFromMemoryAndSetNotificationCallback(
250     lldb::addr_t addr) {
251   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
252   DataExtractor data; // Load command data
253   static ConstString g_dyld_all_image_infos("dyld_all_image_infos");
254   if (ReadMachHeader(addr, &m_dyld.header, &data)) {
255     if (m_dyld.header.filetype == llvm::MachO::MH_DYLINKER) {
256       m_dyld.address = addr;
257       ModuleSP dyld_module_sp;
258       if (ParseLoadCommands(data, m_dyld, &m_dyld.file_spec)) {
259         if (m_dyld.file_spec) {
260           UpdateDYLDImageInfoFromNewImageInfo(m_dyld);
261         }
262       }
263       dyld_module_sp = GetDYLDModule();
264 
265       Target &target = m_process->GetTarget();
266 
267       if (m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS &&
268           dyld_module_sp.get()) {
269         const Symbol *symbol = dyld_module_sp->FindFirstSymbolWithNameAndType(
270             g_dyld_all_image_infos, eSymbolTypeData);
271         if (symbol)
272           m_dyld_all_image_infos_addr = symbol->GetLoadAddress(&target);
273       }
274 
275       // Update all image infos
276       InitializeFromAllImageInfos();
277 
278       // If we didn't have an executable before, but now we do, then the dyld
279       // module shared pointer might be unique and we may need to add it again
280       // (since Target::SetExecutableModule() will clear the images). So append
281       // the dyld module back to the list if it is
282       /// unique!
283       if (dyld_module_sp) {
284         target.GetImages().AppendIfNeeded(dyld_module_sp);
285 
286         // At this point we should have read in dyld's module, and so we should
287         // set breakpoints in it:
288         ModuleList modules;
289         modules.Append(dyld_module_sp);
290         target.ModulesDidLoad(modules);
291         SetDYLDModule(dyld_module_sp);
292       }
293 
294       return true;
295     }
296   }
297   return false;
298 }
299 
NeedToDoInitialImageFetch()300 bool DynamicLoaderMacOSXDYLD::NeedToDoInitialImageFetch() {
301   return m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS;
302 }
303 
304 // Static callback function that gets called when our DYLD notification
305 // breakpoint gets hit. We update all of our image infos and then let our super
306 // class DynamicLoader class decide if we should stop or not (based on global
307 // preference).
NotifyBreakpointHit(void * baton,StoppointCallbackContext * context,lldb::user_id_t break_id,lldb::user_id_t break_loc_id)308 bool DynamicLoaderMacOSXDYLD::NotifyBreakpointHit(
309     void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
310     lldb::user_id_t break_loc_id) {
311   // Let the event know that the images have changed
312   // DYLD passes three arguments to the notification breakpoint.
313   // Arg1: enum dyld_image_mode mode - 0 = adding, 1 = removing Arg2: uint32_t
314   // infoCount        - Number of shared libraries added Arg3: dyld_image_info
315   // info[]    - Array of structs of the form:
316   //                                     const struct mach_header
317   //                                     *imageLoadAddress
318   //                                     const char               *imageFilePath
319   //                                     uintptr_t imageFileModDate (a time_t)
320 
321   DynamicLoaderMacOSXDYLD *dyld_instance = (DynamicLoaderMacOSXDYLD *)baton;
322 
323   // First step is to see if we've already initialized the all image infos.  If
324   // we haven't then this function will do so and return true.  In the course
325   // of initializing the all_image_infos it will read the complete current
326   // state, so we don't need to figure out what has changed from the data
327   // passed in to us.
328 
329   ExecutionContext exe_ctx(context->exe_ctx_ref);
330   Process *process = exe_ctx.GetProcessPtr();
331 
332   // This is a sanity check just in case this dyld_instance is an old dyld
333   // plugin's breakpoint still lying around.
334   if (process != dyld_instance->m_process)
335     return false;
336 
337   if (dyld_instance->InitializeFromAllImageInfos())
338     return dyld_instance->GetStopWhenImagesChange();
339 
340   const lldb::ABISP &abi = process->GetABI();
341   if (abi) {
342     // Build up the value array to store the three arguments given above, then
343     // get the values from the ABI:
344 
345     TypeSystemClang *clang_ast_context =
346         ScratchTypeSystemClang::GetForTarget(process->GetTarget());
347     if (!clang_ast_context)
348       return false;
349 
350     ValueList argument_values;
351     Value input_value;
352 
353     CompilerType clang_void_ptr_type =
354         clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
355     CompilerType clang_uint32_type =
356         clang_ast_context->GetBuiltinTypeForEncodingAndBitSize(
357             lldb::eEncodingUint, 32);
358     input_value.SetValueType(Value::ValueType::Scalar);
359     input_value.SetCompilerType(clang_uint32_type);
360     //        input_value.SetContext (Value::eContextTypeClangType,
361     //        clang_uint32_type);
362     argument_values.PushValue(input_value);
363     argument_values.PushValue(input_value);
364     input_value.SetCompilerType(clang_void_ptr_type);
365     //        input_value.SetContext (Value::eContextTypeClangType,
366     //        clang_void_ptr_type);
367     argument_values.PushValue(input_value);
368 
369     if (abi->GetArgumentValues(exe_ctx.GetThreadRef(), argument_values)) {
370       uint32_t dyld_mode =
371           argument_values.GetValueAtIndex(0)->GetScalar().UInt(-1);
372       if (dyld_mode != static_cast<uint32_t>(-1)) {
373         // Okay the mode was right, now get the number of elements, and the
374         // array of new elements...
375         uint32_t image_infos_count =
376             argument_values.GetValueAtIndex(1)->GetScalar().UInt(-1);
377         if (image_infos_count != static_cast<uint32_t>(-1)) {
378           // Got the number added, now go through the array of added elements,
379           // putting out the mach header address, and adding the image. Note,
380           // I'm not putting in logging here, since the AddModules &
381           // RemoveModules functions do all the logging internally.
382 
383           lldb::addr_t image_infos_addr =
384               argument_values.GetValueAtIndex(2)->GetScalar().ULongLong();
385           if (dyld_mode == 0) {
386             // This is add:
387             dyld_instance->AddModulesUsingImageInfosAddress(image_infos_addr,
388                                                             image_infos_count);
389           } else {
390             // This is remove:
391             dyld_instance->RemoveModulesUsingImageInfosAddress(
392                 image_infos_addr, image_infos_count);
393           }
394         }
395       }
396     }
397   } else {
398     process->GetTarget().GetDebugger().GetAsyncErrorStream()->Printf(
399         "No ABI plugin located for triple %s -- shared libraries will not be "
400         "registered!\n",
401         process->GetTarget().GetArchitecture().GetTriple().getTriple().c_str());
402   }
403 
404   // Return true to stop the target, false to just let the target run
405   return dyld_instance->GetStopWhenImagesChange();
406 }
407 
ReadAllImageInfosStructure()408 bool DynamicLoaderMacOSXDYLD::ReadAllImageInfosStructure() {
409   std::lock_guard<std::recursive_mutex> guard(m_mutex);
410 
411   // the all image infos is already valid for this process stop ID
412   if (m_process->GetStopID() == m_dyld_all_image_infos_stop_id)
413     return true;
414 
415   m_dyld_all_image_infos.Clear();
416   if (m_dyld_all_image_infos_addr != LLDB_INVALID_ADDRESS) {
417     ByteOrder byte_order =
418         m_process->GetTarget().GetArchitecture().GetByteOrder();
419     uint32_t addr_size =
420         m_process->GetTarget().GetArchitecture().GetAddressByteSize();
421 
422     uint8_t buf[256];
423     DataExtractor data(buf, sizeof(buf), byte_order, addr_size);
424     lldb::offset_t offset = 0;
425 
426     const size_t count_v2 = sizeof(uint32_t) + // version
427                             sizeof(uint32_t) + // infoArrayCount
428                             addr_size +        // infoArray
429                             addr_size +        // notification
430                             addr_size + // processDetachedFromSharedRegion +
431                                         // libSystemInitialized + pad
432                             addr_size;  // dyldImageLoadAddress
433     const size_t count_v11 = count_v2 + addr_size +  // jitInfo
434                              addr_size +             // dyldVersion
435                              addr_size +             // errorMessage
436                              addr_size +             // terminationFlags
437                              addr_size +             // coreSymbolicationShmPage
438                              addr_size +             // systemOrderFlag
439                              addr_size +             // uuidArrayCount
440                              addr_size +             // uuidArray
441                              addr_size +             // dyldAllImageInfosAddress
442                              addr_size +             // initialImageCount
443                              addr_size +             // errorKind
444                              addr_size +             // errorClientOfDylibPath
445                              addr_size +             // errorTargetDylibPath
446                              addr_size;              // errorSymbol
447     const size_t count_v13 = count_v11 + addr_size + // sharedCacheSlide
448                              sizeof(uuid_t);         // sharedCacheUUID
449     UNUSED_IF_ASSERT_DISABLED(count_v13);
450     assert(sizeof(buf) >= count_v13);
451 
452     Status error;
453     if (m_process->ReadMemory(m_dyld_all_image_infos_addr, buf, 4, error) ==
454         4) {
455       m_dyld_all_image_infos.version = data.GetU32(&offset);
456       // If anything in the high byte is set, we probably got the byte order
457       // incorrect (the process might not have it set correctly yet due to
458       // attaching to a program without a specified file).
459       if (m_dyld_all_image_infos.version & 0xff000000) {
460         // We have guessed the wrong byte order. Swap it and try reading the
461         // version again.
462         if (byte_order == eByteOrderLittle)
463           byte_order = eByteOrderBig;
464         else
465           byte_order = eByteOrderLittle;
466 
467         data.SetByteOrder(byte_order);
468         offset = 0;
469         m_dyld_all_image_infos.version = data.GetU32(&offset);
470       }
471     } else {
472       return false;
473     }
474 
475     const size_t count =
476         (m_dyld_all_image_infos.version >= 11) ? count_v11 : count_v2;
477 
478     const size_t bytes_read =
479         m_process->ReadMemory(m_dyld_all_image_infos_addr, buf, count, error);
480     if (bytes_read == count) {
481       offset = 0;
482       m_dyld_all_image_infos.version = data.GetU32(&offset);
483       m_dyld_all_image_infos.dylib_info_count = data.GetU32(&offset);
484       m_dyld_all_image_infos.dylib_info_addr = data.GetAddress(&offset);
485       m_dyld_all_image_infos.notification = data.GetAddress(&offset);
486       m_dyld_all_image_infos.processDetachedFromSharedRegion =
487           data.GetU8(&offset);
488       m_dyld_all_image_infos.libSystemInitialized = data.GetU8(&offset);
489       // Adjust for padding.
490       offset += addr_size - 2;
491       m_dyld_all_image_infos.dyldImageLoadAddress = data.GetAddress(&offset);
492       if (m_dyld_all_image_infos.version >= 11) {
493         offset += addr_size * 8;
494         uint64_t dyld_all_image_infos_addr = data.GetAddress(&offset);
495 
496         // When we started, we were given the actual address of the
497         // all_image_infos struct (probably via TASK_DYLD_INFO) in memory -
498         // this address is stored in m_dyld_all_image_infos_addr and is the
499         // most accurate address we have.
500 
501         // We read the dyld_all_image_infos struct from memory; it contains its
502         // own address. If the address in the struct does not match the actual
503         // address, the dyld we're looking at has been loaded at a different
504         // location (slid) from where it intended to load.  The addresses in
505         // the dyld_all_image_infos struct are the original, non-slid
506         // addresses, and need to be adjusted.  Most importantly the address of
507         // dyld and the notification address need to be adjusted.
508 
509         if (dyld_all_image_infos_addr != m_dyld_all_image_infos_addr) {
510           uint64_t image_infos_offset =
511               dyld_all_image_infos_addr -
512               m_dyld_all_image_infos.dyldImageLoadAddress;
513           uint64_t notification_offset =
514               m_dyld_all_image_infos.notification -
515               m_dyld_all_image_infos.dyldImageLoadAddress;
516           m_dyld_all_image_infos.dyldImageLoadAddress =
517               m_dyld_all_image_infos_addr - image_infos_offset;
518           m_dyld_all_image_infos.notification =
519               m_dyld_all_image_infos.dyldImageLoadAddress + notification_offset;
520         }
521       }
522       m_dyld_all_image_infos_stop_id = m_process->GetStopID();
523       return true;
524     }
525   }
526   return false;
527 }
528 
AddModulesUsingImageInfosAddress(lldb::addr_t image_infos_addr,uint32_t image_infos_count)529 bool DynamicLoaderMacOSXDYLD::AddModulesUsingImageInfosAddress(
530     lldb::addr_t image_infos_addr, uint32_t image_infos_count) {
531   ImageInfo::collection image_infos;
532   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
533   LLDB_LOGF(log, "Adding %d modules.\n", image_infos_count);
534 
535   std::lock_guard<std::recursive_mutex> guard(m_mutex);
536   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
537   if (m_process->GetStopID() == m_dyld_image_infos_stop_id)
538     return true;
539 
540   StructuredData::ObjectSP image_infos_json_sp =
541       m_process->GetLoadedDynamicLibrariesInfos(image_infos_addr,
542                                                 image_infos_count);
543   if (image_infos_json_sp.get() && image_infos_json_sp->GetAsDictionary() &&
544       image_infos_json_sp->GetAsDictionary()->HasKey("images") &&
545       image_infos_json_sp->GetAsDictionary()
546           ->GetValueForKey("images")
547           ->GetAsArray() &&
548       image_infos_json_sp->GetAsDictionary()
549               ->GetValueForKey("images")
550               ->GetAsArray()
551               ->GetSize() == image_infos_count) {
552     bool return_value = false;
553     if (JSONImageInformationIntoImageInfo(image_infos_json_sp, image_infos)) {
554       UpdateSpecialBinariesFromNewImageInfos(image_infos);
555       return_value = AddModulesUsingImageInfos(image_infos);
556     }
557     m_dyld_image_infos_stop_id = m_process->GetStopID();
558     return return_value;
559   }
560 
561   if (!ReadImageInfos(image_infos_addr, image_infos_count, image_infos))
562     return false;
563 
564   UpdateImageInfosHeaderAndLoadCommands(image_infos, image_infos_count, false);
565   bool return_value = AddModulesUsingImageInfos(image_infos);
566   m_dyld_image_infos_stop_id = m_process->GetStopID();
567   return return_value;
568 }
569 
RemoveModulesUsingImageInfosAddress(lldb::addr_t image_infos_addr,uint32_t image_infos_count)570 bool DynamicLoaderMacOSXDYLD::RemoveModulesUsingImageInfosAddress(
571     lldb::addr_t image_infos_addr, uint32_t image_infos_count) {
572   ImageInfo::collection image_infos;
573   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
574 
575   std::lock_guard<std::recursive_mutex> guard(m_mutex);
576   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
577   if (m_process->GetStopID() == m_dyld_image_infos_stop_id)
578     return true;
579 
580   // First read in the image_infos for the removed modules, and their headers &
581   // load commands.
582   if (!ReadImageInfos(image_infos_addr, image_infos_count, image_infos)) {
583     if (log)
584       log->PutCString("Failed reading image infos array.");
585     return false;
586   }
587 
588   LLDB_LOGF(log, "Removing %d modules.", image_infos_count);
589 
590   ModuleList unloaded_module_list;
591   for (uint32_t idx = 0; idx < image_infos.size(); ++idx) {
592     if (log) {
593       LLDB_LOGF(log, "Removing module at address=0x%16.16" PRIx64 ".",
594                 image_infos[idx].address);
595       image_infos[idx].PutToLog(log);
596     }
597 
598     // Remove this image_infos from the m_all_image_infos.  We do the
599     // comparison by address rather than by file spec because we can have many
600     // modules with the same "file spec" in the case that they are modules
601     // loaded from memory.
602     //
603     // Also copy over the uuid from the old entry to the removed entry so we
604     // can use it to lookup the module in the module list.
605 
606     ImageInfo::collection::iterator pos, end = m_dyld_image_infos.end();
607     for (pos = m_dyld_image_infos.begin(); pos != end; pos++) {
608       if (image_infos[idx].address == (*pos).address) {
609         image_infos[idx].uuid = (*pos).uuid;
610 
611         // Add the module from this image_info to the "unloaded_module_list".
612         // We'll remove them all at one go later on.
613 
614         ModuleSP unload_image_module_sp(
615             FindTargetModuleForImageInfo(image_infos[idx], false, nullptr));
616         if (unload_image_module_sp.get()) {
617           // When we unload, be sure to use the image info from the old list,
618           // since that has sections correctly filled in.
619           UnloadModuleSections(unload_image_module_sp.get(), *pos);
620           unloaded_module_list.AppendIfNeeded(unload_image_module_sp);
621         } else {
622           if (log) {
623             LLDB_LOGF(log, "Could not find module for unloading info entry:");
624             image_infos[idx].PutToLog(log);
625           }
626         }
627 
628         // Then remove it from the m_dyld_image_infos:
629 
630         m_dyld_image_infos.erase(pos);
631         break;
632       }
633     }
634 
635     if (pos == end) {
636       if (log) {
637         LLDB_LOGF(log, "Could not find image_info entry for unloading image:");
638         image_infos[idx].PutToLog(log);
639       }
640     }
641   }
642   if (unloaded_module_list.GetSize() > 0) {
643     if (log) {
644       log->PutCString("Unloaded:");
645       unloaded_module_list.LogUUIDAndPaths(
646           log, "DynamicLoaderMacOSXDYLD::ModulesDidUnload");
647     }
648     m_process->GetTarget().GetImages().Remove(unloaded_module_list);
649   }
650   m_dyld_image_infos_stop_id = m_process->GetStopID();
651   return true;
652 }
653 
ReadImageInfos(lldb::addr_t image_infos_addr,uint32_t image_infos_count,ImageInfo::collection & image_infos)654 bool DynamicLoaderMacOSXDYLD::ReadImageInfos(
655     lldb::addr_t image_infos_addr, uint32_t image_infos_count,
656     ImageInfo::collection &image_infos) {
657   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
658   const ByteOrder endian = GetByteOrderFromMagic(m_dyld.header.magic);
659   const uint32_t addr_size = m_dyld.GetAddressByteSize();
660 
661   image_infos.resize(image_infos_count);
662   const size_t count = image_infos.size() * 3 * addr_size;
663   DataBufferHeap info_data(count, 0);
664   Status error;
665   const size_t bytes_read = m_process->ReadMemory(
666       image_infos_addr, info_data.GetBytes(), info_data.GetByteSize(), error);
667   if (bytes_read == count) {
668     lldb::offset_t info_data_offset = 0;
669     DataExtractor info_data_ref(info_data.GetBytes(), info_data.GetByteSize(),
670                                 endian, addr_size);
671     for (size_t i = 0;
672          i < image_infos.size() && info_data_ref.ValidOffset(info_data_offset);
673          i++) {
674       image_infos[i].address = info_data_ref.GetAddress(&info_data_offset);
675       lldb::addr_t path_addr = info_data_ref.GetAddress(&info_data_offset);
676       image_infos[i].mod_date = info_data_ref.GetAddress(&info_data_offset);
677 
678       char raw_path[PATH_MAX];
679       m_process->ReadCStringFromMemory(path_addr, raw_path, sizeof(raw_path),
680                                        error);
681       // don't resolve the path
682       if (error.Success()) {
683         image_infos[i].file_spec.SetFile(raw_path, FileSpec::Style::native);
684       }
685     }
686     return true;
687   } else {
688     return false;
689   }
690 }
691 
692 // If we have found where the "_dyld_all_image_infos" lives in memory, read the
693 // current info from it, and then update all image load addresses (or lack
694 // thereof).  Only do this if this is the first time we're reading the dyld
695 // infos.  Return true if we actually read anything, and false otherwise.
InitializeFromAllImageInfos()696 bool DynamicLoaderMacOSXDYLD::InitializeFromAllImageInfos() {
697   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
698 
699   std::lock_guard<std::recursive_mutex> guard(m_mutex);
700   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
701   if (m_process->GetStopID() == m_dyld_image_infos_stop_id ||
702       m_dyld_image_infos.size() != 0)
703     return false;
704 
705   if (ReadAllImageInfosStructure()) {
706     // Nothing to load or unload?
707     if (m_dyld_all_image_infos.dylib_info_count == 0)
708       return true;
709 
710     if (m_dyld_all_image_infos.dylib_info_addr == 0) {
711       // DYLD is updating the images now.  So we should say we have no images,
712       // and then we'll
713       // figure it out when we hit the added breakpoint.
714       return false;
715     } else {
716       if (!AddModulesUsingImageInfosAddress(
717               m_dyld_all_image_infos.dylib_info_addr,
718               m_dyld_all_image_infos.dylib_info_count)) {
719         DEBUG_PRINTF("%s", "unable to read all data for all_dylib_infos.");
720         m_dyld_image_infos.clear();
721       }
722     }
723 
724     // Now we have one more bit of business.  If there is a library left in the
725     // images for our target that doesn't have a load address, then it must be
726     // something that we were expecting to load (for instance we read a load
727     // command for it) but it didn't in fact load - probably because
728     // DYLD_*_PATH pointed to an equivalent version.  We don't want it to stay
729     // in the target's module list or it will confuse us, so unload it here.
730     Target &target = m_process->GetTarget();
731     ModuleList not_loaded_modules;
732     for (ModuleSP module_sp : target.GetImages().Modules()) {
733       if (!module_sp->IsLoadedInTarget(&target)) {
734         if (log) {
735           StreamString s;
736           module_sp->GetDescription(s.AsRawOstream());
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.
ReadMachHeader(lldb::addr_t addr,llvm::MachO::mach_header * header,DataExtractor * load_command_data)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
ParseLoadCommands(const DataExtractor & data,ImageInfo & dylib_info,FileSpec * lc_id_dylinker)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 
UpdateImageInfosHeaderAndLoadCommands(ImageInfo::collection & image_infos,uint32_t infos_count,bool update_executable)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.
PutToLog(Log * log) const970 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 
SetNotificationBreakpoint()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 
CanLoadImage()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 
GetSharedCacheInformation(lldb::addr_t & base_address,UUID & uuid,LazyBool & using_shared_cache,LazyBool & private_shared_cache)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 
IsFullyInitialized()1117 bool DynamicLoaderMacOSXDYLD::IsFullyInitialized() {
1118   if (ReadAllImageInfosStructure())
1119     return m_dyld_all_image_infos.libSystemInitialized;
1120   return false;
1121 }
1122 
Initialize()1123 void DynamicLoaderMacOSXDYLD::Initialize() {
1124   PluginManager::RegisterPlugin(GetPluginNameStatic(),
1125                                 GetPluginDescriptionStatic(), CreateInstance);
1126   DynamicLoaderMacOS::Initialize();
1127 }
1128 
Terminate()1129 void DynamicLoaderMacOSXDYLD::Terminate() {
1130   DynamicLoaderMacOS::Terminate();
1131   PluginManager::UnregisterPlugin(CreateInstance);
1132 }
1133 
GetPluginNameStatic()1134 lldb_private::ConstString DynamicLoaderMacOSXDYLD::GetPluginNameStatic() {
1135   static ConstString g_name("macosx-dyld");
1136   return g_name;
1137 }
1138 
GetPluginDescriptionStatic()1139 const char *DynamicLoaderMacOSXDYLD::GetPluginDescriptionStatic() {
1140   return "Dynamic loader plug-in that watches for shared library loads/unloads "
1141          "in MacOSX user processes.";
1142 }
1143 
1144 // PluginInterface protocol
GetPluginName()1145 lldb_private::ConstString DynamicLoaderMacOSXDYLD::GetPluginName() {
1146   return GetPluginNameStatic();
1147 }
1148 
GetPluginVersion()1149 uint32_t DynamicLoaderMacOSXDYLD::GetPluginVersion() { return 1; }
1150 
AddrByteSize()1151 uint32_t DynamicLoaderMacOSXDYLD::AddrByteSize() {
1152   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
1153 
1154   switch (m_dyld.header.magic) {
1155   case llvm::MachO::MH_MAGIC:
1156   case llvm::MachO::MH_CIGAM:
1157     return 4;
1158 
1159   case llvm::MachO::MH_MAGIC_64:
1160   case llvm::MachO::MH_CIGAM_64:
1161     return 8;
1162 
1163   default:
1164     break;
1165   }
1166   return 0;
1167 }
1168 
GetByteOrderFromMagic(uint32_t magic)1169 lldb::ByteOrder DynamicLoaderMacOSXDYLD::GetByteOrderFromMagic(uint32_t magic) {
1170   switch (magic) {
1171   case llvm::MachO::MH_MAGIC:
1172   case llvm::MachO::MH_MAGIC_64:
1173     return endian::InlHostByteOrder();
1174 
1175   case llvm::MachO::MH_CIGAM:
1176   case llvm::MachO::MH_CIGAM_64:
1177     if (endian::InlHostByteOrder() == lldb::eByteOrderBig)
1178       return lldb::eByteOrderLittle;
1179     else
1180       return lldb::eByteOrderBig;
1181 
1182   default:
1183     break;
1184   }
1185   return lldb::eByteOrderInvalid;
1186 }
1187