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