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