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
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.
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.
80 void DynamicLoaderDarwin::DidLaunch() {
81   PrivateInitialize(m_process);
82   DoInitialImageFetch();
83   SetNotificationBreakpoint();
84 }
85 
86 // Clear out the state of this class.
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 
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 
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 
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.
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.
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             Host::SystemLog(Host::eSystemLogWarning,
341                             "warning: unable to find and unload segment named "
342                             "'%s' in '%s' in macosx dynamic loader plug-in.\n",
343                             info.segments[i].name.AsCString("<invalid>"),
344                             image_object_file->GetFileSpec().GetPath().c_str());
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 
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 
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 
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 
605 void DynamicLoaderDarwin::SetDYLDModule(lldb::ModuleSP &dyld_module_sp) {
606   m_dyld_module_wp = dyld_module_sp;
607 }
608 
609 ModuleSP DynamicLoaderDarwin::GetDYLDModule() {
610   ModuleSP dyld_sp(m_dyld_module_wp.lock());
611   return dyld_sp;
612 }
613 
614 bool DynamicLoaderDarwin::AddModulesUsingImageInfos(
615     ImageInfo::collection &image_infos) {
616   std::lock_guard<std::recursive_mutex> guard(m_mutex);
617   // Now add these images to the main list.
618   ModuleList loaded_module_list;
619   Log *log = GetLog(LLDBLog::DynamicLoader);
620   Target &target = m_process->GetTarget();
621   ModuleList &target_images = target.GetImages();
622 
623   for (uint32_t idx = 0; idx < image_infos.size(); ++idx) {
624     if (log) {
625       LLDB_LOGF(log, "Adding new image at address=0x%16.16" PRIx64 ".",
626                 image_infos[idx].address);
627       image_infos[idx].PutToLog(log);
628     }
629 
630     m_dyld_image_infos.push_back(image_infos[idx]);
631 
632     ModuleSP image_module_sp(
633         FindTargetModuleForImageInfo(image_infos[idx], true, nullptr));
634 
635     if (image_module_sp) {
636       ObjectFile *objfile = image_module_sp->GetObjectFile();
637       if (objfile) {
638         SectionList *sections = objfile->GetSectionList();
639         if (sections) {
640           ConstString commpage_dbstr("__commpage");
641           Section *commpage_section =
642               sections->FindSectionByName(commpage_dbstr).get();
643           if (commpage_section) {
644             ModuleSpec module_spec(objfile->GetFileSpec(),
645                                    image_infos[idx].GetArchitecture());
646             module_spec.GetObjectName() = commpage_dbstr;
647             ModuleSP commpage_image_module_sp(
648                 target_images.FindFirstModule(module_spec));
649             if (!commpage_image_module_sp) {
650               module_spec.SetObjectOffset(objfile->GetFileOffset() +
651                                           commpage_section->GetFileOffset());
652               module_spec.SetObjectSize(objfile->GetByteSize());
653               commpage_image_module_sp = target.GetOrCreateModule(module_spec,
654                                                                true /* notify */);
655               if (!commpage_image_module_sp ||
656                   commpage_image_module_sp->GetObjectFile() == nullptr) {
657                 commpage_image_module_sp = m_process->ReadModuleFromMemory(
658                     image_infos[idx].file_spec, image_infos[idx].address);
659                 // Always load a memory image right away in the target in case
660                 // we end up trying to read the symbol table from memory... The
661                 // __LINKEDIT will need to be mapped so we can figure out where
662                 // the symbol table bits are...
663                 bool changed = false;
664                 UpdateImageLoadAddress(commpage_image_module_sp.get(),
665                                        image_infos[idx]);
666                 target.GetImages().Append(commpage_image_module_sp);
667                 if (changed) {
668                   image_infos[idx].load_stop_id = m_process->GetStopID();
669                   loaded_module_list.AppendIfNeeded(commpage_image_module_sp);
670                 }
671               }
672             }
673           }
674         }
675       }
676 
677       // UpdateImageLoadAddress will return true if any segments change load
678       // address. We need to check this so we don't mention that all loaded
679       // shared libraries are newly loaded each time we hit out dyld breakpoint
680       // since dyld will list all shared libraries each time.
681       if (UpdateImageLoadAddress(image_module_sp.get(), image_infos[idx])) {
682         target_images.AppendIfNeeded(image_module_sp);
683         loaded_module_list.AppendIfNeeded(image_module_sp);
684       }
685 
686       // To support macCatalyst and legacy iOS simulator,
687       // update the module's platform with the DYLD info.
688       ArchSpec dyld_spec = image_infos[idx].GetArchitecture();
689       auto &dyld_triple = dyld_spec.GetTriple();
690       if ((dyld_triple.getEnvironment() == llvm::Triple::MacABI &&
691            dyld_triple.getOS() == llvm::Triple::IOS) ||
692           (dyld_triple.getEnvironment() == llvm::Triple::Simulator &&
693            (dyld_triple.getOS() == llvm::Triple::IOS ||
694             dyld_triple.getOS() == llvm::Triple::TvOS ||
695             dyld_triple.getOS() == llvm::Triple::WatchOS)))
696         image_module_sp->MergeArchitecture(dyld_spec);
697     }
698   }
699 
700   if (loaded_module_list.GetSize() > 0) {
701     if (log)
702       loaded_module_list.LogUUIDAndPaths(log,
703                                          "DynamicLoaderDarwin::ModulesDidLoad");
704     m_process->GetTarget().ModulesDidLoad(loaded_module_list);
705   }
706   return true;
707 }
708 
709 // On Mac OS X libobjc (the Objective-C runtime) has several critical dispatch
710 // functions written in hand-written assembly, and also have hand-written
711 // unwind information in the eh_frame section.  Normally we prefer analyzing
712 // the assembly instructions of a currently executing frame to unwind from that
713 // frame -- but on hand-written functions this profiling can fail.  We should
714 // use the eh_frame instructions for these functions all the time.
715 //
716 // As an aside, it would be better if the eh_frame entries had a flag (or were
717 // extensible so they could have an Apple-specific flag) which indicates that
718 // the instructions are asynchronous -- accurate at every instruction, instead
719 // of our normal default assumption that they are not.
720 
721 bool DynamicLoaderDarwin::AlwaysRelyOnEHUnwindInfo(SymbolContext &sym_ctx) {
722   ModuleSP module_sp;
723   if (sym_ctx.symbol) {
724     module_sp = sym_ctx.symbol->GetAddressRef().GetModule();
725   }
726   if (module_sp.get() == nullptr && sym_ctx.function) {
727     module_sp =
728         sym_ctx.function->GetAddressRange().GetBaseAddress().GetModule();
729   }
730   if (module_sp.get() == nullptr)
731     return false;
732 
733   ObjCLanguageRuntime *objc_runtime = ObjCLanguageRuntime::Get(*m_process);
734   return objc_runtime != nullptr &&
735          objc_runtime->IsModuleObjCLibrary(module_sp);
736 }
737 
738 // Dump a Segment to the file handle provided.
739 void DynamicLoaderDarwin::Segment::PutToLog(Log *log,
740                                             lldb::addr_t slide) const {
741   if (log) {
742     if (slide == 0)
743       LLDB_LOGF(log, "\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ")",
744                 name.AsCString(""), vmaddr + slide, vmaddr + slide + vmsize);
745     else
746       LLDB_LOGF(log,
747                 "\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64
748                 ") slide = 0x%" PRIx64,
749                 name.AsCString(""), vmaddr + slide, vmaddr + slide + vmsize,
750                 slide);
751   }
752 }
753 
754 lldb_private::ArchSpec DynamicLoaderDarwin::ImageInfo::GetArchitecture() const {
755   // Update the module's platform with the DYLD info.
756   lldb_private::ArchSpec arch_spec(lldb_private::eArchTypeMachO, header.cputype,
757                                    header.cpusubtype);
758   if (os_env == llvm::Triple::MacABI && os_type == llvm::Triple::IOS) {
759     llvm::Triple triple(llvm::Twine(arch_spec.GetArchitectureName()) +
760                         "-apple-ios" + min_version_os_sdk + "-macabi");
761     ArchSpec maccatalyst_spec(triple);
762     if (arch_spec.IsCompatibleMatch(maccatalyst_spec))
763       arch_spec.MergeFrom(maccatalyst_spec);
764   }
765   if (os_env == llvm::Triple::Simulator &&
766       (os_type == llvm::Triple::IOS || os_type == llvm::Triple::TvOS ||
767        os_type == llvm::Triple::WatchOS)) {
768     llvm::Triple triple(llvm::Twine(arch_spec.GetArchitectureName()) +
769                         "-apple-" + llvm::Triple::getOSTypeName(os_type) +
770                         min_version_os_sdk + "-simulator");
771     ArchSpec sim_spec(triple);
772     if (arch_spec.IsCompatibleMatch(sim_spec))
773       arch_spec.MergeFrom(sim_spec);
774   }
775   return arch_spec;
776 }
777 
778 const DynamicLoaderDarwin::Segment *
779 DynamicLoaderDarwin::ImageInfo::FindSegment(ConstString name) const {
780   const size_t num_segments = segments.size();
781   for (size_t i = 0; i < num_segments; ++i) {
782     if (segments[i].name == name)
783       return &segments[i];
784   }
785   return nullptr;
786 }
787 
788 // Dump an image info structure to the file handle provided.
789 void DynamicLoaderDarwin::ImageInfo::PutToLog(Log *log) const {
790   if (!log)
791     return;
792   if (address == LLDB_INVALID_ADDRESS) {
793     LLDB_LOG(log, "modtime={0:x+8} uuid={1} path='{2}' (UNLOADED)", mod_date,
794              uuid.GetAsString(), file_spec.GetPath());
795   } else {
796     LLDB_LOG(log, "address={0:x+16} modtime={1:x+8} uuid={2} path='{3}'",
797              address, mod_date, uuid.GetAsString(), file_spec.GetPath());
798     for (uint32_t i = 0; i < segments.size(); ++i)
799       segments[i].PutToLog(log, slide);
800   }
801 }
802 
803 void DynamicLoaderDarwin::PrivateInitialize(Process *process) {
804   DEBUG_PRINTF("DynamicLoaderDarwin::%s() process state = %s\n", __FUNCTION__,
805                StateAsCString(m_process->GetState()));
806   Clear(true);
807   m_process = process;
808   m_process->GetTarget().ClearAllLoadedSections();
809 }
810 
811 // Member function that gets called when the process state changes.
812 void DynamicLoaderDarwin::PrivateProcessStateChanged(Process *process,
813                                                      StateType state) {
814   DEBUG_PRINTF("DynamicLoaderDarwin::%s(%s)\n", __FUNCTION__,
815                StateAsCString(state));
816   switch (state) {
817   case eStateConnected:
818   case eStateAttaching:
819   case eStateLaunching:
820   case eStateInvalid:
821   case eStateUnloaded:
822   case eStateExited:
823   case eStateDetached:
824     Clear(false);
825     break;
826 
827   case eStateStopped:
828     // Keep trying find dyld and set our notification breakpoint each time we
829     // stop until we succeed
830     if (!DidSetNotificationBreakpoint() && m_process->IsAlive()) {
831       if (NeedToDoInitialImageFetch())
832         DoInitialImageFetch();
833 
834       SetNotificationBreakpoint();
835     }
836     break;
837 
838   case eStateRunning:
839   case eStateStepping:
840   case eStateCrashed:
841   case eStateSuspended:
842     break;
843   }
844 }
845 
846 ThreadPlanSP
847 DynamicLoaderDarwin::GetStepThroughTrampolinePlan(Thread &thread,
848                                                   bool stop_others) {
849   ThreadPlanSP thread_plan_sp;
850   StackFrame *current_frame = thread.GetStackFrameAtIndex(0).get();
851   const SymbolContext &current_context =
852       current_frame->GetSymbolContext(eSymbolContextSymbol);
853   Symbol *current_symbol = current_context.symbol;
854   Log *log = GetLog(LLDBLog::Step);
855   TargetSP target_sp(thread.CalculateTarget());
856 
857   if (current_symbol != nullptr) {
858     std::vector<Address> addresses;
859 
860     if (current_symbol->IsTrampoline()) {
861       ConstString trampoline_name =
862           current_symbol->GetMangled().GetName(Mangled::ePreferMangled);
863 
864       if (trampoline_name) {
865         const ModuleList &images = target_sp->GetImages();
866 
867         SymbolContextList code_symbols;
868         images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeCode,
869                                           code_symbols);
870         size_t num_code_symbols = code_symbols.GetSize();
871 
872         if (num_code_symbols > 0) {
873           for (uint32_t i = 0; i < num_code_symbols; i++) {
874             SymbolContext context;
875             AddressRange addr_range;
876             if (code_symbols.GetContextAtIndex(i, context)) {
877               context.GetAddressRange(eSymbolContextEverything, 0, false,
878                                       addr_range);
879               addresses.push_back(addr_range.GetBaseAddress());
880               if (log) {
881                 addr_t load_addr =
882                     addr_range.GetBaseAddress().GetLoadAddress(target_sp.get());
883 
884                 LLDB_LOGF(log,
885                           "Found a trampoline target symbol at 0x%" PRIx64 ".",
886                           load_addr);
887               }
888             }
889           }
890         }
891 
892         SymbolContextList reexported_symbols;
893         images.FindSymbolsWithNameAndType(
894             trampoline_name, eSymbolTypeReExported, reexported_symbols);
895         size_t num_reexported_symbols = reexported_symbols.GetSize();
896         if (num_reexported_symbols > 0) {
897           for (uint32_t i = 0; i < num_reexported_symbols; i++) {
898             SymbolContext context;
899             if (reexported_symbols.GetContextAtIndex(i, context)) {
900               if (context.symbol) {
901                 Symbol *actual_symbol =
902                     context.symbol->ResolveReExportedSymbol(*target_sp.get());
903                 if (actual_symbol) {
904                   const Address actual_symbol_addr =
905                       actual_symbol->GetAddress();
906                   if (actual_symbol_addr.IsValid()) {
907                     addresses.push_back(actual_symbol_addr);
908                     if (log) {
909                       lldb::addr_t load_addr =
910                           actual_symbol_addr.GetLoadAddress(target_sp.get());
911                       LLDB_LOGF(
912                           log,
913                           "Found a re-exported symbol: %s at 0x%" PRIx64 ".",
914                           actual_symbol->GetName().GetCString(), load_addr);
915                     }
916                   }
917                 }
918               }
919             }
920           }
921         }
922 
923         SymbolContextList indirect_symbols;
924         images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeResolver,
925                                           indirect_symbols);
926         size_t num_indirect_symbols = indirect_symbols.GetSize();
927         if (num_indirect_symbols > 0) {
928           for (uint32_t i = 0; i < num_indirect_symbols; i++) {
929             SymbolContext context;
930             AddressRange addr_range;
931             if (indirect_symbols.GetContextAtIndex(i, context)) {
932               context.GetAddressRange(eSymbolContextEverything, 0, false,
933                                       addr_range);
934               addresses.push_back(addr_range.GetBaseAddress());
935               if (log) {
936                 addr_t load_addr =
937                     addr_range.GetBaseAddress().GetLoadAddress(target_sp.get());
938 
939                 LLDB_LOGF(log,
940                           "Found an indirect target symbol at 0x%" PRIx64 ".",
941                           load_addr);
942               }
943             }
944           }
945         }
946       }
947     } else if (current_symbol->GetType() == eSymbolTypeReExported) {
948       // I am not sure we could ever end up stopped AT a re-exported symbol.
949       // But just in case:
950 
951       const Symbol *actual_symbol =
952           current_symbol->ResolveReExportedSymbol(*(target_sp.get()));
953       if (actual_symbol) {
954         Address target_addr(actual_symbol->GetAddress());
955         if (target_addr.IsValid()) {
956           LLDB_LOGF(
957               log,
958               "Found a re-exported symbol: %s pointing to: %s at 0x%" PRIx64
959               ".",
960               current_symbol->GetName().GetCString(),
961               actual_symbol->GetName().GetCString(),
962               target_addr.GetLoadAddress(target_sp.get()));
963           addresses.push_back(target_addr.GetLoadAddress(target_sp.get()));
964         }
965       }
966     }
967 
968     if (addresses.size() > 0) {
969       // First check whether any of the addresses point to Indirect symbols,
970       // and if they do, resolve them:
971       std::vector<lldb::addr_t> load_addrs;
972       for (Address address : addresses) {
973         Symbol *symbol = address.CalculateSymbolContextSymbol();
974         if (symbol && symbol->IsIndirect()) {
975           Status error;
976           Address symbol_address = symbol->GetAddress();
977           addr_t resolved_addr = thread.GetProcess()->ResolveIndirectFunction(
978               &symbol_address, error);
979           if (error.Success()) {
980             load_addrs.push_back(resolved_addr);
981             LLDB_LOGF(log,
982                       "ResolveIndirectFunction found resolved target for "
983                       "%s at 0x%" PRIx64 ".",
984                       symbol->GetName().GetCString(), resolved_addr);
985           }
986         } else {
987           load_addrs.push_back(address.GetLoadAddress(target_sp.get()));
988         }
989       }
990       thread_plan_sp = std::make_shared<ThreadPlanRunToAddress>(
991           thread, load_addrs, stop_others);
992     }
993   } else {
994     LLDB_LOGF(log, "Could not find symbol for step through.");
995   }
996 
997   return thread_plan_sp;
998 }
999 
1000 void DynamicLoaderDarwin::FindEquivalentSymbols(
1001     lldb_private::Symbol *original_symbol, lldb_private::ModuleList &images,
1002     lldb_private::SymbolContextList &equivalent_symbols) {
1003   ConstString trampoline_name =
1004       original_symbol->GetMangled().GetName(Mangled::ePreferMangled);
1005   if (!trampoline_name)
1006     return;
1007 
1008   static const char *resolver_name_regex = "(_gc|_non_gc|\\$[A-Za-z0-9\\$]+)$";
1009   std::string equivalent_regex_buf("^");
1010   equivalent_regex_buf.append(trampoline_name.GetCString());
1011   equivalent_regex_buf.append(resolver_name_regex);
1012 
1013   RegularExpression equivalent_name_regex(equivalent_regex_buf);
1014   images.FindSymbolsMatchingRegExAndType(equivalent_name_regex, eSymbolTypeCode,
1015                                          equivalent_symbols);
1016 
1017 }
1018 
1019 lldb::ModuleSP DynamicLoaderDarwin::GetPThreadLibraryModule() {
1020   ModuleSP module_sp = m_libpthread_module_wp.lock();
1021   if (!module_sp) {
1022     SymbolContextList sc_list;
1023     ModuleSpec module_spec;
1024     module_spec.GetFileSpec().GetFilename().SetCString(
1025         "libsystem_pthread.dylib");
1026     ModuleList module_list;
1027     m_process->GetTarget().GetImages().FindModules(module_spec, module_list);
1028     if (!module_list.IsEmpty()) {
1029       if (module_list.GetSize() == 1) {
1030         module_sp = module_list.GetModuleAtIndex(0);
1031         if (module_sp)
1032           m_libpthread_module_wp = module_sp;
1033       }
1034     }
1035   }
1036   return module_sp;
1037 }
1038 
1039 Address DynamicLoaderDarwin::GetPthreadSetSpecificAddress() {
1040   if (!m_pthread_getspecific_addr.IsValid()) {
1041     ModuleSP module_sp = GetPThreadLibraryModule();
1042     if (module_sp) {
1043       lldb_private::SymbolContextList sc_list;
1044       module_sp->FindSymbolsWithNameAndType(ConstString("pthread_getspecific"),
1045                                             eSymbolTypeCode, sc_list);
1046       SymbolContext sc;
1047       if (sc_list.GetContextAtIndex(0, sc)) {
1048         if (sc.symbol)
1049           m_pthread_getspecific_addr = sc.symbol->GetAddress();
1050       }
1051     }
1052   }
1053   return m_pthread_getspecific_addr;
1054 }
1055 
1056 lldb::addr_t
1057 DynamicLoaderDarwin::GetThreadLocalData(const lldb::ModuleSP module_sp,
1058                                         const lldb::ThreadSP thread_sp,
1059                                         lldb::addr_t tls_file_addr) {
1060   if (!thread_sp || !module_sp)
1061     return LLDB_INVALID_ADDRESS;
1062 
1063   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1064 
1065   const uint32_t addr_size = m_process->GetAddressByteSize();
1066   uint8_t buf[sizeof(lldb::addr_t) * 3];
1067 
1068   lldb_private::Address tls_addr;
1069   if (module_sp->ResolveFileAddress(tls_file_addr, tls_addr)) {
1070     Status error;
1071     const size_t tsl_data_size = addr_size * 3;
1072     Target &target = m_process->GetTarget();
1073     if (target.ReadMemory(tls_addr, buf, tsl_data_size, error, true) ==
1074         tsl_data_size) {
1075       const ByteOrder byte_order = m_process->GetByteOrder();
1076       DataExtractor data(buf, sizeof(buf), byte_order, addr_size);
1077       lldb::offset_t offset = addr_size; // Skip the first pointer
1078       const lldb::addr_t pthread_key = data.GetAddress(&offset);
1079       const lldb::addr_t tls_offset = data.GetAddress(&offset);
1080       if (pthread_key != 0) {
1081         // First check to see if we have already figured out the location of
1082         // TLS data for the pthread_key on a specific thread yet. If we have we
1083         // can re-use it since its location will not change unless the process
1084         // execs.
1085         const tid_t tid = thread_sp->GetID();
1086         auto tid_pos = m_tid_to_tls_map.find(tid);
1087         if (tid_pos != m_tid_to_tls_map.end()) {
1088           auto tls_pos = tid_pos->second.find(pthread_key);
1089           if (tls_pos != tid_pos->second.end()) {
1090             return tls_pos->second + tls_offset;
1091           }
1092         }
1093         StackFrameSP frame_sp = thread_sp->GetStackFrameAtIndex(0);
1094         if (frame_sp) {
1095           TypeSystemClang *clang_ast_context =
1096               ScratchTypeSystemClang::GetForTarget(target);
1097 
1098           if (!clang_ast_context)
1099             return LLDB_INVALID_ADDRESS;
1100 
1101           CompilerType clang_void_ptr_type =
1102               clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
1103           Address pthread_getspecific_addr = GetPthreadSetSpecificAddress();
1104           if (pthread_getspecific_addr.IsValid()) {
1105             EvaluateExpressionOptions options;
1106 
1107             lldb::ThreadPlanSP thread_plan_sp(new ThreadPlanCallFunction(
1108                 *thread_sp, pthread_getspecific_addr, clang_void_ptr_type,
1109                 llvm::ArrayRef<lldb::addr_t>(pthread_key), options));
1110 
1111             DiagnosticManager execution_errors;
1112             ExecutionContext exe_ctx(thread_sp);
1113             lldb::ExpressionResults results = m_process->RunThreadPlan(
1114                 exe_ctx, thread_plan_sp, options, execution_errors);
1115 
1116             if (results == lldb::eExpressionCompleted) {
1117               lldb::ValueObjectSP result_valobj_sp =
1118                   thread_plan_sp->GetReturnValueObject();
1119               if (result_valobj_sp) {
1120                 const lldb::addr_t pthread_key_data =
1121                     result_valobj_sp->GetValueAsUnsigned(0);
1122                 if (pthread_key_data) {
1123                   m_tid_to_tls_map[tid].insert(
1124                       std::make_pair(pthread_key, pthread_key_data));
1125                   return pthread_key_data + tls_offset;
1126                 }
1127               }
1128             }
1129           }
1130         }
1131       }
1132     }
1133   }
1134   return LLDB_INVALID_ADDRESS;
1135 }
1136 
1137 bool DynamicLoaderDarwin::UseDYLDSPI(Process *process) {
1138   Log *log = GetLog(LLDBLog::DynamicLoader);
1139   bool use_new_spi_interface = false;
1140 
1141   llvm::VersionTuple version = process->GetHostOSVersion();
1142   if (!version.empty()) {
1143     const llvm::Triple::OSType os_type =
1144         process->GetTarget().GetArchitecture().GetTriple().getOS();
1145 
1146     // macOS 10.12 and newer
1147     if (os_type == llvm::Triple::MacOSX &&
1148         version >= llvm::VersionTuple(10, 12))
1149       use_new_spi_interface = true;
1150 
1151     // iOS 10 and newer
1152     if (os_type == llvm::Triple::IOS && version >= llvm::VersionTuple(10))
1153       use_new_spi_interface = true;
1154 
1155     // tvOS 10 and newer
1156     if (os_type == llvm::Triple::TvOS && version >= llvm::VersionTuple(10))
1157       use_new_spi_interface = true;
1158 
1159     // watchOS 3 and newer
1160     if (os_type == llvm::Triple::WatchOS && version >= llvm::VersionTuple(3))
1161       use_new_spi_interface = true;
1162 
1163     // NEED_BRIDGEOS_TRIPLE // Any BridgeOS
1164     // NEED_BRIDGEOS_TRIPLE if (os_type == llvm::Triple::BridgeOS)
1165     // NEED_BRIDGEOS_TRIPLE   use_new_spi_interface = true;
1166   }
1167 
1168   if (log) {
1169     if (use_new_spi_interface)
1170       LLDB_LOGF(
1171           log, "DynamicLoaderDarwin::UseDYLDSPI: Use new DynamicLoader plugin");
1172     else
1173       LLDB_LOGF(
1174           log, "DynamicLoaderDarwin::UseDYLDSPI: Use old DynamicLoader plugin");
1175   }
1176   return use_new_spi_interface;
1177 }
1178