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