1 //===-- DynamicLoaderDarwin.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 "DynamicLoaderDarwin.h"
10 
11 #include "lldb/Breakpoint/StoppointCallbackContext.h"
12 #include "lldb/Core/Debugger.h"
13 #include "lldb/Core/Module.h"
14 #include "lldb/Core/ModuleSpec.h"
15 #include "lldb/Core/PluginManager.h"
16 #include "lldb/Core/Section.h"
17 #include "lldb/Expression/DiagnosticManager.h"
18 #include "lldb/Host/FileSystem.h"
19 #include "lldb/Host/HostInfo.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/ThreadPlanCallFunction.h"
28 #include "lldb/Target/ThreadPlanRunToAddress.h"
29 #include "lldb/Utility/DataBuffer.h"
30 #include "lldb/Utility/DataBufferHeap.h"
31 #include "lldb/Utility/Log.h"
32 #include "lldb/Utility/State.h"
33 
34 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
35 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
36 
37 //#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN
38 #ifdef ENABLE_DEBUG_PRINTF
39 #include <cstdio>
40 #define DEBUG_PRINTF(fmt, ...) printf(fmt, ##__VA_ARGS__)
41 #else
42 #define DEBUG_PRINTF(fmt, ...)
43 #endif
44 
45 #ifndef __APPLE__
46 #include "Utility/UuidCompatibility.h"
47 #else
48 #include <uuid/uuid.h>
49 #endif
50 
51 #include <memory>
52 
53 using namespace lldb;
54 using namespace lldb_private;
55 
56 // Constructor
DynamicLoaderDarwin(Process * process)57 DynamicLoaderDarwin::DynamicLoaderDarwin(Process *process)
58     : DynamicLoader(process), m_dyld_module_wp(), m_libpthread_module_wp(),
59       m_pthread_getspecific_addr(), m_tid_to_tls_map(), m_dyld_image_infos(),
60       m_dyld_image_infos_stop_id(UINT32_MAX), m_dyld(), m_mutex() {}
61 
62 // Destructor
63 DynamicLoaderDarwin::~DynamicLoaderDarwin() = default;
64 
65 /// Called after attaching a process.
66 ///
67 /// Allow DynamicLoader plug-ins to execute some code after
68 /// attaching to a process.
DidAttach()69 void DynamicLoaderDarwin::DidAttach() {
70   PrivateInitialize(m_process);
71   DoInitialImageFetch();
72   SetNotificationBreakpoint();
73 }
74 
75 /// Called after attaching a process.
76 ///
77 /// Allow DynamicLoader plug-ins to execute some code after
78 /// attaching to a process.
DidLaunch()79 void DynamicLoaderDarwin::DidLaunch() {
80   PrivateInitialize(m_process);
81   DoInitialImageFetch();
82   SetNotificationBreakpoint();
83 }
84 
85 // Clear out the state of this class.
Clear(bool clear_process)86 void DynamicLoaderDarwin::Clear(bool clear_process) {
87   std::lock_guard<std::recursive_mutex> guard(m_mutex);
88   if (clear_process)
89     m_process = nullptr;
90   m_dyld_image_infos.clear();
91   m_dyld_image_infos_stop_id = UINT32_MAX;
92   m_dyld.Clear(false);
93 }
94 
FindTargetModuleForImageInfo(ImageInfo & image_info,bool can_create,bool * did_create_ptr)95 ModuleSP DynamicLoaderDarwin::FindTargetModuleForImageInfo(
96     ImageInfo &image_info, bool can_create, bool *did_create_ptr) {
97   if (did_create_ptr)
98     *did_create_ptr = false;
99 
100   Target &target = m_process->GetTarget();
101   const ModuleList &target_images = target.GetImages();
102   ModuleSpec module_spec(image_info.file_spec);
103   module_spec.GetUUID() = image_info.uuid;
104 
105   // macCatalyst support: Request matching os/environment.
106   {
107     auto &target_triple = target.GetArchitecture().GetTriple();
108     if (target_triple.getOS() == llvm::Triple::IOS &&
109         target_triple.getEnvironment() == llvm::Triple::MacABI) {
110       // Request the macCatalyst variant of frameworks that have both
111       // a PLATFORM_MACOS and a PLATFORM_MACCATALYST load command.
112       module_spec.GetArchitecture() = ArchSpec(target_triple);
113     }
114   }
115 
116   ModuleSP module_sp(target_images.FindFirstModule(module_spec));
117 
118   if (module_sp && !module_spec.GetUUID().IsValid() &&
119       !module_sp->GetUUID().IsValid()) {
120     // No UUID, we must rely upon the cached module modification time and the
121     // modification time of the file on disk
122     if (module_sp->GetModificationTime() !=
123         FileSystem::Instance().GetModificationTime(module_sp->GetFileSpec()))
124       module_sp.reset();
125   }
126 
127   if (module_sp || !can_create)
128     return module_sp;
129 
130   if (HostInfo::GetArchitecture().IsCompatibleMatch(target.GetArchitecture())) {
131     // When debugging on the host, we are most likely using the same shared
132     // cache as our inferior. The dylibs from the shared cache might not
133     // exist on the filesystem, so let's use the images in our own memory
134     // to create the modules.
135     // Check if the requested image is in our shared cache.
136     SharedCacheImageInfo image_info =
137         HostInfo::GetSharedCacheImageInfo(module_spec.GetFileSpec().GetPath());
138 
139     // If we found it and it has the correct UUID, let's proceed with
140     // creating a module from the memory contents.
141     if (image_info.uuid &&
142         (!module_spec.GetUUID() || module_spec.GetUUID() == image_info.uuid)) {
143       ModuleSpec shared_cache_spec(module_spec.GetFileSpec(), image_info.uuid,
144                                    image_info.data_sp);
145       module_sp =
146           target.GetOrCreateModule(shared_cache_spec, false /* notify */);
147     }
148   }
149   // We'll call Target::ModulesDidLoad after all the modules have been
150   // added to the target, don't let it be called for every one.
151   if (!module_sp)
152     module_sp = target.GetOrCreateModule(module_spec, false /* notify */);
153   if (!module_sp || module_sp->GetObjectFile() == nullptr)
154     module_sp = m_process->ReadModuleFromMemory(image_info.file_spec,
155                                                 image_info.address);
156 
157   if (did_create_ptr)
158     *did_create_ptr = (bool)module_sp;
159 
160   return module_sp;
161 }
162 
UnloadImages(const std::vector<lldb::addr_t> & solib_addresses)163 void DynamicLoaderDarwin::UnloadImages(
164     const std::vector<lldb::addr_t> &solib_addresses) {
165   std::lock_guard<std::recursive_mutex> guard(m_mutex);
166   if (m_process->GetStopID() == m_dyld_image_infos_stop_id)
167     return;
168 
169   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
170   Target &target = m_process->GetTarget();
171   LLDB_LOGF(log, "Removing %" PRId64 " modules.",
172             (uint64_t)solib_addresses.size());
173 
174   ModuleList unloaded_module_list;
175 
176   for (addr_t solib_addr : solib_addresses) {
177     Address header;
178     if (header.SetLoadAddress(solib_addr, &target)) {
179       if (header.GetOffset() == 0) {
180         ModuleSP module_to_remove(header.GetModule());
181         if (module_to_remove.get()) {
182           LLDB_LOGF(log, "Removing module at address 0x%" PRIx64, solib_addr);
183           // remove the sections from the Target
184           UnloadSections(module_to_remove);
185           // add this to the list of modules to remove
186           unloaded_module_list.AppendIfNeeded(module_to_remove);
187           // remove the entry from the m_dyld_image_infos
188           ImageInfo::collection::iterator pos, end = m_dyld_image_infos.end();
189           for (pos = m_dyld_image_infos.begin(); pos != end; pos++) {
190             if (solib_addr == (*pos).address) {
191               m_dyld_image_infos.erase(pos);
192               break;
193             }
194           }
195         }
196       }
197     }
198   }
199 
200   if (unloaded_module_list.GetSize() > 0) {
201     if (log) {
202       log->PutCString("Unloaded:");
203       unloaded_module_list.LogUUIDAndPaths(
204           log, "DynamicLoaderDarwin::UnloadModules");
205     }
206     m_process->GetTarget().GetImages().Remove(unloaded_module_list);
207     m_dyld_image_infos_stop_id = m_process->GetStopID();
208   }
209 }
210 
UnloadAllImages()211 void DynamicLoaderDarwin::UnloadAllImages() {
212   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
213   ModuleList unloaded_modules_list;
214 
215   Target &target = m_process->GetTarget();
216   const ModuleList &target_modules = target.GetImages();
217   std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
218 
219   ModuleSP dyld_sp(GetDYLDModule());
220   for (ModuleSP module_sp : target_modules.Modules()) {
221     // Don't remove dyld - else we'll lose our breakpoint notifying us about
222     // libraries being re-loaded...
223     if (module_sp && module_sp != dyld_sp) {
224       UnloadSections(module_sp);
225       unloaded_modules_list.Append(module_sp);
226     }
227   }
228 
229   if (unloaded_modules_list.GetSize() != 0) {
230     if (log) {
231       log->PutCString("Unloaded:");
232       unloaded_modules_list.LogUUIDAndPaths(
233           log, "DynamicLoaderDarwin::UnloadAllImages");
234     }
235     target.GetImages().Remove(unloaded_modules_list);
236     m_dyld_image_infos.clear();
237     m_dyld_image_infos_stop_id = m_process->GetStopID();
238   }
239 }
240 
241 // Update the load addresses for all segments in MODULE using the updated INFO
242 // that is passed in.
UpdateImageLoadAddress(Module * module,ImageInfo & info)243 bool DynamicLoaderDarwin::UpdateImageLoadAddress(Module *module,
244                                                  ImageInfo &info) {
245   bool changed = false;
246   if (module) {
247     ObjectFile *image_object_file = module->GetObjectFile();
248     if (image_object_file) {
249       SectionList *section_list = image_object_file->GetSectionList();
250       if (section_list) {
251         std::vector<uint32_t> inaccessible_segment_indexes;
252         // We now know the slide amount, so go through all sections and update
253         // the load addresses with the correct values.
254         const size_t num_segments = info.segments.size();
255         for (size_t i = 0; i < num_segments; ++i) {
256           // Only load a segment if it has protections. Things like __PAGEZERO
257           // don't have any protections, and they shouldn't be slid
258           SectionSP section_sp(
259               section_list->FindSectionByName(info.segments[i].name));
260 
261           if (info.segments[i].maxprot == 0) {
262             inaccessible_segment_indexes.push_back(i);
263           } else {
264             const addr_t new_section_load_addr =
265                 info.segments[i].vmaddr + info.slide;
266             static ConstString g_section_name_LINKEDIT("__LINKEDIT");
267 
268             if (section_sp) {
269               // __LINKEDIT sections from files in the shared cache can overlap
270               // so check to see what the segment name is and pass "false" so
271               // we don't warn of overlapping "Section" objects, and "true" for
272               // all other sections.
273               const bool warn_multiple =
274                   section_sp->GetName() != g_section_name_LINKEDIT;
275 
276               changed = m_process->GetTarget().SetSectionLoadAddress(
277                   section_sp, new_section_load_addr, warn_multiple);
278             }
279           }
280         }
281 
282         // If the loaded the file (it changed) and we have segments that are
283         // not readable or writeable, add them to the invalid memory region
284         // cache for the process. This will typically only be the __PAGEZERO
285         // segment in the main executable. We might be able to apply this more
286         // generally to more sections that have no protections in the future,
287         // but for now we are going to just do __PAGEZERO.
288         if (changed && !inaccessible_segment_indexes.empty()) {
289           for (uint32_t i = 0; i < inaccessible_segment_indexes.size(); ++i) {
290             const uint32_t seg_idx = inaccessible_segment_indexes[i];
291             SectionSP section_sp(
292                 section_list->FindSectionByName(info.segments[seg_idx].name));
293 
294             if (section_sp) {
295               static ConstString g_pagezero_section_name("__PAGEZERO");
296               if (g_pagezero_section_name == section_sp->GetName()) {
297                 // __PAGEZERO never slides...
298                 const lldb::addr_t vmaddr = info.segments[seg_idx].vmaddr;
299                 const lldb::addr_t vmsize = info.segments[seg_idx].vmsize;
300                 Process::LoadRange pagezero_range(vmaddr, vmsize);
301                 m_process->AddInvalidMemoryRegion(pagezero_range);
302               }
303             }
304           }
305         }
306       }
307     }
308   }
309   // We might have an in memory image that was loaded as soon as it was created
310   if (info.load_stop_id == m_process->GetStopID())
311     changed = true;
312   else if (changed) {
313     // Update the stop ID when this library was updated
314     info.load_stop_id = m_process->GetStopID();
315   }
316   return changed;
317 }
318 
319 // Unload the segments in MODULE using the INFO that is passed in.
UnloadModuleSections(Module * module,ImageInfo & info)320 bool DynamicLoaderDarwin::UnloadModuleSections(Module *module,
321                                                ImageInfo &info) {
322   bool changed = false;
323   if (module) {
324     ObjectFile *image_object_file = module->GetObjectFile();
325     if (image_object_file) {
326       SectionList *section_list = image_object_file->GetSectionList();
327       if (section_list) {
328         const size_t num_segments = info.segments.size();
329         for (size_t i = 0; i < num_segments; ++i) {
330           SectionSP section_sp(
331               section_list->FindSectionByName(info.segments[i].name));
332           if (section_sp) {
333             const addr_t old_section_load_addr =
334                 info.segments[i].vmaddr + info.slide;
335             if (m_process->GetTarget().SetSectionUnloaded(
336                     section_sp, old_section_load_addr))
337               changed = true;
338           } else {
339             Host::SystemLog(Host::eSystemLogWarning,
340                             "warning: unable to find and unload segment named "
341                             "'%s' in '%s' in macosx dynamic loader plug-in.\n",
342                             info.segments[i].name.AsCString("<invalid>"),
343                             image_object_file->GetFileSpec().GetPath().c_str());
344           }
345         }
346       }
347     }
348   }
349   return changed;
350 }
351 
352 // Given a JSON dictionary (from debugserver, most likely) of binary images
353 // loaded in the inferior process, add the images to the ImageInfo collection.
354 
JSONImageInformationIntoImageInfo(StructuredData::ObjectSP image_details,ImageInfo::collection & image_infos)355 bool DynamicLoaderDarwin::JSONImageInformationIntoImageInfo(
356     StructuredData::ObjectSP image_details,
357     ImageInfo::collection &image_infos) {
358   StructuredData::ObjectSP images_sp =
359       image_details->GetAsDictionary()->GetValueForKey("images");
360   if (images_sp.get() == nullptr)
361     return false;
362 
363   image_infos.resize(images_sp->GetAsArray()->GetSize());
364 
365   for (size_t i = 0; i < image_infos.size(); i++) {
366     StructuredData::ObjectSP image_sp =
367         images_sp->GetAsArray()->GetItemAtIndex(i);
368     if (image_sp.get() == nullptr || image_sp->GetAsDictionary() == nullptr)
369       return false;
370     StructuredData::Dictionary *image = image_sp->GetAsDictionary();
371     // clang-format off
372     if (!image->HasKey("load_address") ||
373         !image->HasKey("pathname") ||
374         !image->HasKey("mod_date") ||
375         !image->HasKey("mach_header") ||
376         image->GetValueForKey("mach_header")->GetAsDictionary() == nullptr ||
377         !image->HasKey("segments") ||
378         image->GetValueForKey("segments")->GetAsArray() == nullptr ||
379         !image->HasKey("uuid")) {
380       return false;
381     }
382     // clang-format on
383     image_infos[i].address =
384         image->GetValueForKey("load_address")->GetAsInteger()->GetValue();
385     image_infos[i].mod_date =
386         image->GetValueForKey("mod_date")->GetAsInteger()->GetValue();
387     image_infos[i].file_spec.SetFile(
388         image->GetValueForKey("pathname")->GetAsString()->GetValue(),
389         FileSpec::Style::native);
390 
391     StructuredData::Dictionary *mh =
392         image->GetValueForKey("mach_header")->GetAsDictionary();
393     image_infos[i].header.magic =
394         mh->GetValueForKey("magic")->GetAsInteger()->GetValue();
395     image_infos[i].header.cputype =
396         mh->GetValueForKey("cputype")->GetAsInteger()->GetValue();
397     image_infos[i].header.cpusubtype =
398         mh->GetValueForKey("cpusubtype")->GetAsInteger()->GetValue();
399     image_infos[i].header.filetype =
400         mh->GetValueForKey("filetype")->GetAsInteger()->GetValue();
401 
402     if (image->HasKey("min_version_os_name")) {
403       std::string os_name =
404           std::string(image->GetValueForKey("min_version_os_name")
405                           ->GetAsString()
406                           ->GetValue());
407       if (os_name == "macosx")
408         image_infos[i].os_type = llvm::Triple::MacOSX;
409       else if (os_name == "ios" || os_name == "iphoneos")
410         image_infos[i].os_type = llvm::Triple::IOS;
411       else if (os_name == "tvos")
412         image_infos[i].os_type = llvm::Triple::TvOS;
413       else if (os_name == "watchos")
414         image_infos[i].os_type = llvm::Triple::WatchOS;
415       // NEED_BRIDGEOS_TRIPLE else if (os_name == "bridgeos")
416       // NEED_BRIDGEOS_TRIPLE   image_infos[i].os_type = llvm::Triple::BridgeOS;
417       else if (os_name == "maccatalyst") {
418         image_infos[i].os_type = llvm::Triple::IOS;
419         image_infos[i].os_env = llvm::Triple::MacABI;
420       } else if (os_name == "iossimulator") {
421         image_infos[i].os_type = llvm::Triple::IOS;
422         image_infos[i].os_env = llvm::Triple::Simulator;
423       } else if (os_name == "tvossimulator") {
424         image_infos[i].os_type = llvm::Triple::TvOS;
425         image_infos[i].os_env = llvm::Triple::Simulator;
426       } else if (os_name == "watchossimulator") {
427         image_infos[i].os_type = llvm::Triple::WatchOS;
428         image_infos[i].os_env = llvm::Triple::Simulator;
429       }
430     }
431     if (image->HasKey("min_version_os_sdk")) {
432       image_infos[i].min_version_os_sdk =
433           std::string(image->GetValueForKey("min_version_os_sdk")
434                           ->GetAsString()
435                           ->GetValue());
436     }
437 
438     // Fields that aren't used by DynamicLoaderDarwin so debugserver doesn't
439     // currently send them in the reply.
440 
441     if (mh->HasKey("flags"))
442       image_infos[i].header.flags =
443           mh->GetValueForKey("flags")->GetAsInteger()->GetValue();
444     else
445       image_infos[i].header.flags = 0;
446 
447     if (mh->HasKey("ncmds"))
448       image_infos[i].header.ncmds =
449           mh->GetValueForKey("ncmds")->GetAsInteger()->GetValue();
450     else
451       image_infos[i].header.ncmds = 0;
452 
453     if (mh->HasKey("sizeofcmds"))
454       image_infos[i].header.sizeofcmds =
455           mh->GetValueForKey("sizeofcmds")->GetAsInteger()->GetValue();
456     else
457       image_infos[i].header.sizeofcmds = 0;
458 
459     StructuredData::Array *segments =
460         image->GetValueForKey("segments")->GetAsArray();
461     uint32_t segcount = segments->GetSize();
462     for (size_t j = 0; j < segcount; j++) {
463       Segment segment;
464       StructuredData::Dictionary *seg =
465           segments->GetItemAtIndex(j)->GetAsDictionary();
466       segment.name =
467           ConstString(seg->GetValueForKey("name")->GetAsString()->GetValue());
468       segment.vmaddr =
469           seg->GetValueForKey("vmaddr")->GetAsInteger()->GetValue();
470       segment.vmsize =
471           seg->GetValueForKey("vmsize")->GetAsInteger()->GetValue();
472       segment.fileoff =
473           seg->GetValueForKey("fileoff")->GetAsInteger()->GetValue();
474       segment.filesize =
475           seg->GetValueForKey("filesize")->GetAsInteger()->GetValue();
476       segment.maxprot =
477           seg->GetValueForKey("maxprot")->GetAsInteger()->GetValue();
478 
479       // Fields that aren't used by DynamicLoaderDarwin so debugserver doesn't
480       // currently send them in the reply.
481 
482       if (seg->HasKey("initprot"))
483         segment.initprot =
484             seg->GetValueForKey("initprot")->GetAsInteger()->GetValue();
485       else
486         segment.initprot = 0;
487 
488       if (seg->HasKey("flags"))
489         segment.flags =
490             seg->GetValueForKey("flags")->GetAsInteger()->GetValue();
491       else
492         segment.flags = 0;
493 
494       if (seg->HasKey("nsects"))
495         segment.nsects =
496             seg->GetValueForKey("nsects")->GetAsInteger()->GetValue();
497       else
498         segment.nsects = 0;
499 
500       image_infos[i].segments.push_back(segment);
501     }
502 
503     image_infos[i].uuid.SetFromOptionalStringRef(
504         image->GetValueForKey("uuid")->GetAsString()->GetValue());
505 
506     // All sections listed in the dyld image info structure will all either be
507     // fixed up already, or they will all be off by a single slide amount that
508     // is determined by finding the first segment that is at file offset zero
509     // which also has bytes (a file size that is greater than zero) in the
510     // object file.
511 
512     // Determine the slide amount (if any)
513     const size_t num_sections = image_infos[i].segments.size();
514     for (size_t k = 0; k < num_sections; ++k) {
515       // Iterate through the object file sections to find the first section
516       // that starts of file offset zero and that has bytes in the file...
517       if ((image_infos[i].segments[k].fileoff == 0 &&
518            image_infos[i].segments[k].filesize > 0) ||
519           (image_infos[i].segments[k].name == "__TEXT")) {
520         image_infos[i].slide =
521             image_infos[i].address - image_infos[i].segments[k].vmaddr;
522         // We have found the slide amount, so we can exit this for loop.
523         break;
524       }
525     }
526   }
527 
528   return true;
529 }
530 
UpdateSpecialBinariesFromNewImageInfos(ImageInfo::collection & image_infos)531 void DynamicLoaderDarwin::UpdateSpecialBinariesFromNewImageInfos(
532     ImageInfo::collection &image_infos) {
533   uint32_t exe_idx = UINT32_MAX;
534   uint32_t dyld_idx = UINT32_MAX;
535   Target &target = m_process->GetTarget();
536   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
537   ConstString g_dyld_sim_filename("dyld_sim");
538 
539   ArchSpec target_arch = target.GetArchitecture();
540   const size_t image_infos_size = image_infos.size();
541   for (size_t i = 0; i < image_infos_size; i++) {
542     if (image_infos[i].header.filetype == llvm::MachO::MH_DYLINKER) {
543       // In a "simulator" process (an x86 process that is
544       // ios/tvos/watchos/bridgeos) we will have two dyld modules --
545       // a "dyld" that we want to keep track of, and a "dyld_sim" which
546       // we don't need to keep track of here. If the target is an x86
547       // system and the OS of the dyld binary is ios/tvos/watchos/bridgeos,
548       // then we are looking at dyld_sym.
549 
550       // debugserver has only recently (late 2016) started sending up the os
551       // type for each binary it sees -- so if we don't have an os type, use a
552       // filename check as our next best guess.
553       if (image_infos[i].os_type == llvm::Triple::OSType::UnknownOS) {
554         if (image_infos[i].file_spec.GetFilename() != g_dyld_sim_filename) {
555           dyld_idx = i;
556         }
557       } else if (target_arch.GetTriple().getArch() == llvm::Triple::x86 ||
558                  target_arch.GetTriple().getArch() == llvm::Triple::x86_64) {
559         if (image_infos[i].os_type != llvm::Triple::OSType::IOS &&
560             image_infos[i].os_type != llvm::Triple::TvOS &&
561             image_infos[i].os_type != llvm::Triple::WatchOS) {
562             // NEED_BRIDGEOS_TRIPLE image_infos[i].os_type != llvm::Triple::BridgeOS) {
563           dyld_idx = i;
564         }
565       }
566       else {
567         // catch-all for any other environment -- trust that dyld is actually
568         // dyld
569         dyld_idx = i;
570       }
571     } else if (image_infos[i].header.filetype == llvm::MachO::MH_EXECUTE) {
572       exe_idx = i;
573     }
574   }
575 
576   // Set the target executable if we haven't found one so far.
577   if (exe_idx != UINT32_MAX && !target.GetExecutableModule()) {
578     const bool can_create = true;
579     ModuleSP exe_module_sp(FindTargetModuleForImageInfo(image_infos[exe_idx],
580                                                         can_create, nullptr));
581     if (exe_module_sp) {
582       LLDB_LOGF(log, "Found executable module: %s",
583                 exe_module_sp->GetFileSpec().GetPath().c_str());
584       target.GetImages().AppendIfNeeded(exe_module_sp);
585       UpdateImageLoadAddress(exe_module_sp.get(), image_infos[exe_idx]);
586       if (exe_module_sp.get() != target.GetExecutableModulePointer()) {
587         target.SetExecutableModule(exe_module_sp, eLoadDependentsNo);
588       }
589     }
590   }
591 
592   if (dyld_idx != UINT32_MAX) {
593     const bool can_create = true;
594     ModuleSP dyld_sp = FindTargetModuleForImageInfo(image_infos[dyld_idx],
595                                                     can_create, nullptr);
596     if (dyld_sp.get()) {
597       LLDB_LOGF(log, "Found dyld module: %s",
598                 dyld_sp->GetFileSpec().GetPath().c_str());
599       target.GetImages().AppendIfNeeded(dyld_sp);
600       UpdateImageLoadAddress(dyld_sp.get(), image_infos[dyld_idx]);
601       SetDYLDModule(dyld_sp);
602     }
603   }
604 }
605 
UpdateDYLDImageInfoFromNewImageInfo(ImageInfo & image_info)606 void DynamicLoaderDarwin::UpdateDYLDImageInfoFromNewImageInfo(
607     ImageInfo &image_info) {
608   if (image_info.header.filetype == llvm::MachO::MH_DYLINKER) {
609     const bool can_create = true;
610     ModuleSP dyld_sp =
611         FindTargetModuleForImageInfo(image_info, can_create, nullptr);
612     if (dyld_sp.get()) {
613       Target &target = m_process->GetTarget();
614       target.GetImages().AppendIfNeeded(dyld_sp);
615       UpdateImageLoadAddress(dyld_sp.get(), image_info);
616       SetDYLDModule(dyld_sp);
617     }
618   }
619 }
620 
SetDYLDModule(lldb::ModuleSP & dyld_module_sp)621 void DynamicLoaderDarwin::SetDYLDModule(lldb::ModuleSP &dyld_module_sp) {
622   m_dyld_module_wp = dyld_module_sp;
623 }
624 
GetDYLDModule()625 ModuleSP DynamicLoaderDarwin::GetDYLDModule() {
626   ModuleSP dyld_sp(m_dyld_module_wp.lock());
627   return dyld_sp;
628 }
629 
AddModulesUsingImageInfos(ImageInfo::collection & image_infos)630 bool DynamicLoaderDarwin::AddModulesUsingImageInfos(
631     ImageInfo::collection &image_infos) {
632   std::lock_guard<std::recursive_mutex> guard(m_mutex);
633   // Now add these images to the main list.
634   ModuleList loaded_module_list;
635   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
636   Target &target = m_process->GetTarget();
637   ModuleList &target_images = target.GetImages();
638 
639   for (uint32_t idx = 0; idx < image_infos.size(); ++idx) {
640     if (log) {
641       LLDB_LOGF(log, "Adding new image at address=0x%16.16" PRIx64 ".",
642                 image_infos[idx].address);
643       image_infos[idx].PutToLog(log);
644     }
645 
646     m_dyld_image_infos.push_back(image_infos[idx]);
647 
648     ModuleSP image_module_sp(
649         FindTargetModuleForImageInfo(image_infos[idx], true, nullptr));
650 
651     if (image_module_sp) {
652       ObjectFile *objfile = image_module_sp->GetObjectFile();
653       if (objfile) {
654         SectionList *sections = objfile->GetSectionList();
655         if (sections) {
656           ConstString commpage_dbstr("__commpage");
657           Section *commpage_section =
658               sections->FindSectionByName(commpage_dbstr).get();
659           if (commpage_section) {
660             ModuleSpec module_spec(objfile->GetFileSpec(),
661                                    image_infos[idx].GetArchitecture());
662             module_spec.GetObjectName() = commpage_dbstr;
663             ModuleSP commpage_image_module_sp(
664                 target_images.FindFirstModule(module_spec));
665             if (!commpage_image_module_sp) {
666               module_spec.SetObjectOffset(objfile->GetFileOffset() +
667                                           commpage_section->GetFileOffset());
668               module_spec.SetObjectSize(objfile->GetByteSize());
669               commpage_image_module_sp = target.GetOrCreateModule(module_spec,
670                                                                true /* notify */);
671               if (!commpage_image_module_sp ||
672                   commpage_image_module_sp->GetObjectFile() == nullptr) {
673                 commpage_image_module_sp = m_process->ReadModuleFromMemory(
674                     image_infos[idx].file_spec, image_infos[idx].address);
675                 // Always load a memory image right away in the target in case
676                 // we end up trying to read the symbol table from memory... The
677                 // __LINKEDIT will need to be mapped so we can figure out where
678                 // the symbol table bits are...
679                 bool changed = false;
680                 UpdateImageLoadAddress(commpage_image_module_sp.get(),
681                                        image_infos[idx]);
682                 target.GetImages().Append(commpage_image_module_sp);
683                 if (changed) {
684                   image_infos[idx].load_stop_id = m_process->GetStopID();
685                   loaded_module_list.AppendIfNeeded(commpage_image_module_sp);
686                 }
687               }
688             }
689           }
690         }
691       }
692 
693       // UpdateImageLoadAddress will return true if any segments change load
694       // address. We need to check this so we don't mention that all loaded
695       // shared libraries are newly loaded each time we hit out dyld breakpoint
696       // since dyld will list all shared libraries each time.
697       if (UpdateImageLoadAddress(image_module_sp.get(), image_infos[idx])) {
698         target_images.AppendIfNeeded(image_module_sp);
699         loaded_module_list.AppendIfNeeded(image_module_sp);
700       }
701 
702       // To support macCatalyst and legacy iOS simulator,
703       // update the module's platform with the DYLD info.
704       ArchSpec dyld_spec = image_infos[idx].GetArchitecture();
705       auto &dyld_triple = dyld_spec.GetTriple();
706       if ((dyld_triple.getEnvironment() == llvm::Triple::MacABI &&
707            dyld_triple.getOS() == llvm::Triple::IOS) ||
708           (dyld_triple.getEnvironment() == llvm::Triple::Simulator &&
709            (dyld_triple.getOS() == llvm::Triple::IOS ||
710             dyld_triple.getOS() == llvm::Triple::TvOS ||
711             dyld_triple.getOS() == llvm::Triple::WatchOS)))
712         image_module_sp->MergeArchitecture(dyld_spec);
713     }
714   }
715 
716   if (loaded_module_list.GetSize() > 0) {
717     if (log)
718       loaded_module_list.LogUUIDAndPaths(log,
719                                          "DynamicLoaderDarwin::ModulesDidLoad");
720     m_process->GetTarget().ModulesDidLoad(loaded_module_list);
721   }
722   return true;
723 }
724 
725 // On Mac OS X libobjc (the Objective-C runtime) has several critical dispatch
726 // functions written in hand-written assembly, and also have hand-written
727 // unwind information in the eh_frame section.  Normally we prefer analyzing
728 // the assembly instructions of a currently executing frame to unwind from that
729 // frame -- but on hand-written functions this profiling can fail.  We should
730 // use the eh_frame instructions for these functions all the time.
731 //
732 // As an aside, it would be better if the eh_frame entries had a flag (or were
733 // extensible so they could have an Apple-specific flag) which indicates that
734 // the instructions are asynchronous -- accurate at every instruction, instead
735 // of our normal default assumption that they are not.
736 
AlwaysRelyOnEHUnwindInfo(SymbolContext & sym_ctx)737 bool DynamicLoaderDarwin::AlwaysRelyOnEHUnwindInfo(SymbolContext &sym_ctx) {
738   ModuleSP module_sp;
739   if (sym_ctx.symbol) {
740     module_sp = sym_ctx.symbol->GetAddressRef().GetModule();
741   }
742   if (module_sp.get() == nullptr && sym_ctx.function) {
743     module_sp =
744         sym_ctx.function->GetAddressRange().GetBaseAddress().GetModule();
745   }
746   if (module_sp.get() == nullptr)
747     return false;
748 
749   ObjCLanguageRuntime *objc_runtime = ObjCLanguageRuntime::Get(*m_process);
750   return objc_runtime != nullptr &&
751          objc_runtime->IsModuleObjCLibrary(module_sp);
752 }
753 
754 // Dump a Segment to the file handle provided.
PutToLog(Log * log,lldb::addr_t slide) const755 void DynamicLoaderDarwin::Segment::PutToLog(Log *log,
756                                             lldb::addr_t slide) const {
757   if (log) {
758     if (slide == 0)
759       LLDB_LOGF(log, "\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ")",
760                 name.AsCString(""), vmaddr + slide, vmaddr + slide + vmsize);
761     else
762       LLDB_LOGF(log,
763                 "\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64
764                 ") slide = 0x%" PRIx64,
765                 name.AsCString(""), vmaddr + slide, vmaddr + slide + vmsize,
766                 slide);
767   }
768 }
769 
GetArchitecture() const770 lldb_private::ArchSpec DynamicLoaderDarwin::ImageInfo::GetArchitecture() const {
771   // Update the module's platform with the DYLD info.
772   lldb_private::ArchSpec arch_spec(lldb_private::eArchTypeMachO, header.cputype,
773                                    header.cpusubtype);
774   if (os_env == llvm::Triple::MacABI && os_type == llvm::Triple::IOS) {
775     llvm::Triple triple(llvm::Twine(arch_spec.GetArchitectureName()) +
776                         "-apple-ios" + min_version_os_sdk + "-macabi");
777     ArchSpec maccatalyst_spec(triple);
778     if (arch_spec.IsCompatibleMatch(maccatalyst_spec))
779       arch_spec.MergeFrom(maccatalyst_spec);
780   }
781   if (os_env == llvm::Triple::Simulator &&
782       (os_type == llvm::Triple::IOS || os_type == llvm::Triple::TvOS ||
783        os_type == llvm::Triple::WatchOS)) {
784     llvm::Triple triple(llvm::Twine(arch_spec.GetArchitectureName()) +
785                         "-apple-" + llvm::Triple::getOSTypeName(os_type) +
786                         min_version_os_sdk + "-simulator");
787     ArchSpec sim_spec(triple);
788     if (arch_spec.IsCompatibleMatch(sim_spec))
789       arch_spec.MergeFrom(sim_spec);
790   }
791   return arch_spec;
792 }
793 
794 const DynamicLoaderDarwin::Segment *
FindSegment(ConstString name) const795 DynamicLoaderDarwin::ImageInfo::FindSegment(ConstString name) const {
796   const size_t num_segments = segments.size();
797   for (size_t i = 0; i < num_segments; ++i) {
798     if (segments[i].name == name)
799       return &segments[i];
800   }
801   return nullptr;
802 }
803 
804 // Dump an image info structure to the file handle provided.
PutToLog(Log * log) const805 void DynamicLoaderDarwin::ImageInfo::PutToLog(Log *log) const {
806   if (!log)
807     return;
808   if (address == LLDB_INVALID_ADDRESS) {
809     LLDB_LOG(log, "modtime={0:x+8} uuid={1} path='{2}' (UNLOADED)", mod_date,
810              uuid.GetAsString(), file_spec.GetPath());
811   } else {
812     LLDB_LOG(log, "address={0:x+16} modtime={1:x+8} uuid={2} path='{3}'",
813              address, mod_date, uuid.GetAsString(), file_spec.GetPath());
814     for (uint32_t i = 0; i < segments.size(); ++i)
815       segments[i].PutToLog(log, slide);
816   }
817 }
818 
PrivateInitialize(Process * process)819 void DynamicLoaderDarwin::PrivateInitialize(Process *process) {
820   DEBUG_PRINTF("DynamicLoaderDarwin::%s() process state = %s\n", __FUNCTION__,
821                StateAsCString(m_process->GetState()));
822   Clear(true);
823   m_process = process;
824   m_process->GetTarget().ClearAllLoadedSections();
825 }
826 
827 // Member function that gets called when the process state changes.
PrivateProcessStateChanged(Process * process,StateType state)828 void DynamicLoaderDarwin::PrivateProcessStateChanged(Process *process,
829                                                      StateType state) {
830   DEBUG_PRINTF("DynamicLoaderDarwin::%s(%s)\n", __FUNCTION__,
831                StateAsCString(state));
832   switch (state) {
833   case eStateConnected:
834   case eStateAttaching:
835   case eStateLaunching:
836   case eStateInvalid:
837   case eStateUnloaded:
838   case eStateExited:
839   case eStateDetached:
840     Clear(false);
841     break;
842 
843   case eStateStopped:
844     // Keep trying find dyld and set our notification breakpoint each time we
845     // stop until we succeed
846     if (!DidSetNotificationBreakpoint() && m_process->IsAlive()) {
847       if (NeedToDoInitialImageFetch())
848         DoInitialImageFetch();
849 
850       SetNotificationBreakpoint();
851     }
852     break;
853 
854   case eStateRunning:
855   case eStateStepping:
856   case eStateCrashed:
857   case eStateSuspended:
858     break;
859   }
860 }
861 
862 ThreadPlanSP
GetStepThroughTrampolinePlan(Thread & thread,bool stop_others)863 DynamicLoaderDarwin::GetStepThroughTrampolinePlan(Thread &thread,
864                                                   bool stop_others) {
865   ThreadPlanSP thread_plan_sp;
866   StackFrame *current_frame = thread.GetStackFrameAtIndex(0).get();
867   const SymbolContext &current_context =
868       current_frame->GetSymbolContext(eSymbolContextSymbol);
869   Symbol *current_symbol = current_context.symbol;
870   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
871   TargetSP target_sp(thread.CalculateTarget());
872 
873   if (current_symbol != nullptr) {
874     std::vector<Address> addresses;
875 
876     if (current_symbol->IsTrampoline()) {
877       ConstString trampoline_name =
878           current_symbol->GetMangled().GetName(Mangled::ePreferMangled);
879 
880       if (trampoline_name) {
881         const ModuleList &images = target_sp->GetImages();
882 
883         SymbolContextList code_symbols;
884         images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeCode,
885                                           code_symbols);
886         size_t num_code_symbols = code_symbols.GetSize();
887 
888         if (num_code_symbols > 0) {
889           for (uint32_t i = 0; i < num_code_symbols; i++) {
890             SymbolContext context;
891             AddressRange addr_range;
892             if (code_symbols.GetContextAtIndex(i, context)) {
893               context.GetAddressRange(eSymbolContextEverything, 0, false,
894                                       addr_range);
895               addresses.push_back(addr_range.GetBaseAddress());
896               if (log) {
897                 addr_t load_addr =
898                     addr_range.GetBaseAddress().GetLoadAddress(target_sp.get());
899 
900                 LLDB_LOGF(log,
901                           "Found a trampoline target symbol at 0x%" PRIx64 ".",
902                           load_addr);
903               }
904             }
905           }
906         }
907 
908         SymbolContextList reexported_symbols;
909         images.FindSymbolsWithNameAndType(
910             trampoline_name, eSymbolTypeReExported, reexported_symbols);
911         size_t num_reexported_symbols = reexported_symbols.GetSize();
912         if (num_reexported_symbols > 0) {
913           for (uint32_t i = 0; i < num_reexported_symbols; i++) {
914             SymbolContext context;
915             if (reexported_symbols.GetContextAtIndex(i, context)) {
916               if (context.symbol) {
917                 Symbol *actual_symbol =
918                     context.symbol->ResolveReExportedSymbol(*target_sp.get());
919                 if (actual_symbol) {
920                   const Address actual_symbol_addr =
921                       actual_symbol->GetAddress();
922                   if (actual_symbol_addr.IsValid()) {
923                     addresses.push_back(actual_symbol_addr);
924                     if (log) {
925                       lldb::addr_t load_addr =
926                           actual_symbol_addr.GetLoadAddress(target_sp.get());
927                       LLDB_LOGF(
928                           log,
929                           "Found a re-exported symbol: %s at 0x%" PRIx64 ".",
930                           actual_symbol->GetName().GetCString(), load_addr);
931                     }
932                   }
933                 }
934               }
935             }
936           }
937         }
938 
939         SymbolContextList indirect_symbols;
940         images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeResolver,
941                                           indirect_symbols);
942         size_t num_indirect_symbols = indirect_symbols.GetSize();
943         if (num_indirect_symbols > 0) {
944           for (uint32_t i = 0; i < num_indirect_symbols; i++) {
945             SymbolContext context;
946             AddressRange addr_range;
947             if (indirect_symbols.GetContextAtIndex(i, context)) {
948               context.GetAddressRange(eSymbolContextEverything, 0, false,
949                                       addr_range);
950               addresses.push_back(addr_range.GetBaseAddress());
951               if (log) {
952                 addr_t load_addr =
953                     addr_range.GetBaseAddress().GetLoadAddress(target_sp.get());
954 
955                 LLDB_LOGF(log,
956                           "Found an indirect target symbol at 0x%" PRIx64 ".",
957                           load_addr);
958               }
959             }
960           }
961         }
962       }
963     } else if (current_symbol->GetType() == eSymbolTypeReExported) {
964       // I am not sure we could ever end up stopped AT a re-exported symbol.
965       // But just in case:
966 
967       const Symbol *actual_symbol =
968           current_symbol->ResolveReExportedSymbol(*(target_sp.get()));
969       if (actual_symbol) {
970         Address target_addr(actual_symbol->GetAddress());
971         if (target_addr.IsValid()) {
972           LLDB_LOGF(
973               log,
974               "Found a re-exported symbol: %s pointing to: %s at 0x%" PRIx64
975               ".",
976               current_symbol->GetName().GetCString(),
977               actual_symbol->GetName().GetCString(),
978               target_addr.GetLoadAddress(target_sp.get()));
979           addresses.push_back(target_addr.GetLoadAddress(target_sp.get()));
980         }
981       }
982     }
983 
984     if (addresses.size() > 0) {
985       // First check whether any of the addresses point to Indirect symbols,
986       // and if they do, resolve them:
987       std::vector<lldb::addr_t> load_addrs;
988       for (Address address : addresses) {
989         Symbol *symbol = address.CalculateSymbolContextSymbol();
990         if (symbol && symbol->IsIndirect()) {
991           Status error;
992           Address symbol_address = symbol->GetAddress();
993           addr_t resolved_addr = thread.GetProcess()->ResolveIndirectFunction(
994               &symbol_address, error);
995           if (error.Success()) {
996             load_addrs.push_back(resolved_addr);
997             LLDB_LOGF(log,
998                       "ResolveIndirectFunction found resolved target for "
999                       "%s at 0x%" PRIx64 ".",
1000                       symbol->GetName().GetCString(), resolved_addr);
1001           }
1002         } else {
1003           load_addrs.push_back(address.GetLoadAddress(target_sp.get()));
1004         }
1005       }
1006       thread_plan_sp = std::make_shared<ThreadPlanRunToAddress>(
1007           thread, load_addrs, stop_others);
1008     }
1009   } else {
1010     LLDB_LOGF(log, "Could not find symbol for step through.");
1011   }
1012 
1013   return thread_plan_sp;
1014 }
1015 
FindEquivalentSymbols(lldb_private::Symbol * original_symbol,lldb_private::ModuleList & images,lldb_private::SymbolContextList & equivalent_symbols)1016 void DynamicLoaderDarwin::FindEquivalentSymbols(
1017     lldb_private::Symbol *original_symbol, lldb_private::ModuleList &images,
1018     lldb_private::SymbolContextList &equivalent_symbols) {
1019   ConstString trampoline_name =
1020       original_symbol->GetMangled().GetName(Mangled::ePreferMangled);
1021   if (!trampoline_name)
1022     return;
1023 
1024   static const char *resolver_name_regex = "(_gc|_non_gc|\\$[A-Za-z0-9\\$]+)$";
1025   std::string equivalent_regex_buf("^");
1026   equivalent_regex_buf.append(trampoline_name.GetCString());
1027   equivalent_regex_buf.append(resolver_name_regex);
1028 
1029   RegularExpression equivalent_name_regex(equivalent_regex_buf);
1030   images.FindSymbolsMatchingRegExAndType(equivalent_name_regex, eSymbolTypeCode,
1031                                          equivalent_symbols);
1032 
1033 }
1034 
GetPThreadLibraryModule()1035 lldb::ModuleSP DynamicLoaderDarwin::GetPThreadLibraryModule() {
1036   ModuleSP module_sp = m_libpthread_module_wp.lock();
1037   if (!module_sp) {
1038     SymbolContextList sc_list;
1039     ModuleSpec module_spec;
1040     module_spec.GetFileSpec().GetFilename().SetCString(
1041         "libsystem_pthread.dylib");
1042     ModuleList module_list;
1043     m_process->GetTarget().GetImages().FindModules(module_spec, module_list);
1044     if (!module_list.IsEmpty()) {
1045       if (module_list.GetSize() == 1) {
1046         module_sp = module_list.GetModuleAtIndex(0);
1047         if (module_sp)
1048           m_libpthread_module_wp = module_sp;
1049       }
1050     }
1051   }
1052   return module_sp;
1053 }
1054 
GetPthreadSetSpecificAddress()1055 Address DynamicLoaderDarwin::GetPthreadSetSpecificAddress() {
1056   if (!m_pthread_getspecific_addr.IsValid()) {
1057     ModuleSP module_sp = GetPThreadLibraryModule();
1058     if (module_sp) {
1059       lldb_private::SymbolContextList sc_list;
1060       module_sp->FindSymbolsWithNameAndType(ConstString("pthread_getspecific"),
1061                                             eSymbolTypeCode, sc_list);
1062       SymbolContext sc;
1063       if (sc_list.GetContextAtIndex(0, sc)) {
1064         if (sc.symbol)
1065           m_pthread_getspecific_addr = sc.symbol->GetAddress();
1066       }
1067     }
1068   }
1069   return m_pthread_getspecific_addr;
1070 }
1071 
1072 lldb::addr_t
GetThreadLocalData(const lldb::ModuleSP module_sp,const lldb::ThreadSP thread_sp,lldb::addr_t tls_file_addr)1073 DynamicLoaderDarwin::GetThreadLocalData(const lldb::ModuleSP module_sp,
1074                                         const lldb::ThreadSP thread_sp,
1075                                         lldb::addr_t tls_file_addr) {
1076   if (!thread_sp || !module_sp)
1077     return LLDB_INVALID_ADDRESS;
1078 
1079   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1080 
1081   const uint32_t addr_size = m_process->GetAddressByteSize();
1082   uint8_t buf[sizeof(lldb::addr_t) * 3];
1083 
1084   lldb_private::Address tls_addr;
1085   if (module_sp->ResolveFileAddress(tls_file_addr, tls_addr)) {
1086     Status error;
1087     const size_t tsl_data_size = addr_size * 3;
1088     Target &target = m_process->GetTarget();
1089     if (target.ReadMemory(tls_addr, buf, tsl_data_size, error, true) ==
1090         tsl_data_size) {
1091       const ByteOrder byte_order = m_process->GetByteOrder();
1092       DataExtractor data(buf, sizeof(buf), byte_order, addr_size);
1093       lldb::offset_t offset = addr_size; // Skip the first pointer
1094       const lldb::addr_t pthread_key = data.GetAddress(&offset);
1095       const lldb::addr_t tls_offset = data.GetAddress(&offset);
1096       if (pthread_key != 0) {
1097         // First check to see if we have already figured out the location of
1098         // TLS data for the pthread_key on a specific thread yet. If we have we
1099         // can re-use it since its location will not change unless the process
1100         // execs.
1101         const tid_t tid = thread_sp->GetID();
1102         auto tid_pos = m_tid_to_tls_map.find(tid);
1103         if (tid_pos != m_tid_to_tls_map.end()) {
1104           auto tls_pos = tid_pos->second.find(pthread_key);
1105           if (tls_pos != tid_pos->second.end()) {
1106             return tls_pos->second + tls_offset;
1107           }
1108         }
1109         StackFrameSP frame_sp = thread_sp->GetStackFrameAtIndex(0);
1110         if (frame_sp) {
1111           TypeSystemClang *clang_ast_context =
1112               ScratchTypeSystemClang::GetForTarget(target);
1113 
1114           if (!clang_ast_context)
1115             return LLDB_INVALID_ADDRESS;
1116 
1117           CompilerType clang_void_ptr_type =
1118               clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
1119           Address pthread_getspecific_addr = GetPthreadSetSpecificAddress();
1120           if (pthread_getspecific_addr.IsValid()) {
1121             EvaluateExpressionOptions options;
1122 
1123             lldb::ThreadPlanSP thread_plan_sp(new ThreadPlanCallFunction(
1124                 *thread_sp, pthread_getspecific_addr, clang_void_ptr_type,
1125                 llvm::ArrayRef<lldb::addr_t>(pthread_key), options));
1126 
1127             DiagnosticManager execution_errors;
1128             ExecutionContext exe_ctx(thread_sp);
1129             lldb::ExpressionResults results = m_process->RunThreadPlan(
1130                 exe_ctx, thread_plan_sp, options, execution_errors);
1131 
1132             if (results == lldb::eExpressionCompleted) {
1133               lldb::ValueObjectSP result_valobj_sp =
1134                   thread_plan_sp->GetReturnValueObject();
1135               if (result_valobj_sp) {
1136                 const lldb::addr_t pthread_key_data =
1137                     result_valobj_sp->GetValueAsUnsigned(0);
1138                 if (pthread_key_data) {
1139                   m_tid_to_tls_map[tid].insert(
1140                       std::make_pair(pthread_key, pthread_key_data));
1141                   return pthread_key_data + tls_offset;
1142                 }
1143               }
1144             }
1145           }
1146         }
1147       }
1148     }
1149   }
1150   return LLDB_INVALID_ADDRESS;
1151 }
1152 
UseDYLDSPI(Process * process)1153 bool DynamicLoaderDarwin::UseDYLDSPI(Process *process) {
1154   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
1155   bool use_new_spi_interface = false;
1156 
1157   llvm::VersionTuple version = process->GetHostOSVersion();
1158   if (!version.empty()) {
1159     const llvm::Triple::OSType os_type =
1160         process->GetTarget().GetArchitecture().GetTriple().getOS();
1161 
1162     // macOS 10.12 and newer
1163     if (os_type == llvm::Triple::MacOSX &&
1164         version >= llvm::VersionTuple(10, 12))
1165       use_new_spi_interface = true;
1166 
1167     // iOS 10 and newer
1168     if (os_type == llvm::Triple::IOS && version >= llvm::VersionTuple(10))
1169       use_new_spi_interface = true;
1170 
1171     // tvOS 10 and newer
1172     if (os_type == llvm::Triple::TvOS && version >= llvm::VersionTuple(10))
1173       use_new_spi_interface = true;
1174 
1175     // watchOS 3 and newer
1176     if (os_type == llvm::Triple::WatchOS && version >= llvm::VersionTuple(3))
1177       use_new_spi_interface = true;
1178 
1179     // NEED_BRIDGEOS_TRIPLE // Any BridgeOS
1180     // NEED_BRIDGEOS_TRIPLE if (os_type == llvm::Triple::BridgeOS)
1181     // NEED_BRIDGEOS_TRIPLE   use_new_spi_interface = true;
1182   }
1183 
1184   if (log) {
1185     if (use_new_spi_interface)
1186       LLDB_LOGF(
1187           log, "DynamicLoaderDarwin::UseDYLDSPI: Use new DynamicLoader plugin");
1188     else
1189       LLDB_LOGF(
1190           log, "DynamicLoaderDarwin::UseDYLDSPI: Use old DynamicLoader plugin");
1191   }
1192   return use_new_spi_interface;
1193 }
1194