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