180814287SRaphael Isemann //===-- DynamicLoaderDarwin.cpp -------------------------------------------===//
25fe4d141SJason Molenda //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
65fe4d141SJason Molenda //
75fe4d141SJason Molenda //===----------------------------------------------------------------------===//
85fe4d141SJason Molenda 
91408bf72SPavel Labath #include "DynamicLoaderDarwin.h"
101408bf72SPavel Labath 
115fe4d141SJason Molenda #include "lldb/Breakpoint/StoppointCallbackContext.h"
125fe4d141SJason Molenda #include "lldb/Core/Debugger.h"
135fe4d141SJason Molenda #include "lldb/Core/Module.h"
145fe4d141SJason Molenda #include "lldb/Core/ModuleSpec.h"
155fe4d141SJason Molenda #include "lldb/Core/PluginManager.h"
165fe4d141SJason Molenda #include "lldb/Core/Section.h"
175fe4d141SJason Molenda #include "lldb/Expression/DiagnosticManager.h"
181408bf72SPavel Labath #include "lldb/Host/FileSystem.h"
198113a8bbSFred Riss #include "lldb/Host/HostInfo.h"
205fe4d141SJason Molenda #include "lldb/Symbol/Function.h"
215fe4d141SJason Molenda #include "lldb/Symbol/ObjectFile.h"
225fe4d141SJason Molenda #include "lldb/Target/ABI.h"
235fe4d141SJason Molenda #include "lldb/Target/RegisterContext.h"
245fe4d141SJason Molenda #include "lldb/Target/StackFrame.h"
255fe4d141SJason Molenda #include "lldb/Target/Target.h"
265fe4d141SJason Molenda #include "lldb/Target/Thread.h"
275fe4d141SJason Molenda #include "lldb/Target/ThreadPlanCallFunction.h"
285fe4d141SJason Molenda #include "lldb/Target/ThreadPlanRunToAddress.h"
29666cc0b2SZachary Turner #include "lldb/Utility/DataBuffer.h"
30666cc0b2SZachary Turner #include "lldb/Utility/DataBufferHeap.h"
31c34698a8SPavel Labath #include "lldb/Utility/LLDBLog.h"
326f9e6901SZachary Turner #include "lldb/Utility/Log.h"
33d821c997SPavel Labath #include "lldb/Utility/State.h"
345fe4d141SJason Molenda 
35b5701710SAlex Langford #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
368be30215SAlex Langford #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
37b5701710SAlex Langford 
385fe4d141SJason Molenda //#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN
395fe4d141SJason Molenda #ifdef ENABLE_DEBUG_PRINTF
4076e47d48SRaphael Isemann #include <cstdio>
415fe4d141SJason Molenda #define DEBUG_PRINTF(fmt, ...) printf(fmt, ##__VA_ARGS__)
425fe4d141SJason Molenda #else
435fe4d141SJason Molenda #define DEBUG_PRINTF(fmt, ...)
445fe4d141SJason Molenda #endif
455fe4d141SJason Molenda 
465fe4d141SJason Molenda #ifndef __APPLE__
475fe4d141SJason Molenda #include "Utility/UuidCompatibility.h"
485fe4d141SJason Molenda #else
495fe4d141SJason Molenda #include <uuid/uuid.h>
505fe4d141SJason Molenda #endif
515fe4d141SJason Molenda 
52796ac80bSJonas Devlieghere #include <memory>
53796ac80bSJonas Devlieghere 
545fe4d141SJason Molenda using namespace lldb;
555fe4d141SJason Molenda using namespace lldb_private;
565fe4d141SJason Molenda 
575fe4d141SJason Molenda // Constructor
DynamicLoaderDarwin(Process * process)585fe4d141SJason Molenda DynamicLoaderDarwin::DynamicLoaderDarwin(Process *process)
59b9c1b51eSKate Stone     : DynamicLoader(process), m_dyld_module_wp(), m_libpthread_module_wp(),
60b9c1b51eSKate Stone       m_pthread_getspecific_addr(), m_tid_to_tls_map(), m_dyld_image_infos(),
61b9c1b51eSKate Stone       m_dyld_image_infos_stop_id(UINT32_MAX), m_dyld(), m_mutex() {}
625fe4d141SJason Molenda 
635fe4d141SJason Molenda // Destructor
64fd2433e1SJonas Devlieghere DynamicLoaderDarwin::~DynamicLoaderDarwin() = default;
655fe4d141SJason Molenda 
665fe4d141SJason Molenda /// Called after attaching a process.
675fe4d141SJason Molenda ///
685fe4d141SJason Molenda /// Allow DynamicLoader plug-ins to execute some code after
695fe4d141SJason Molenda /// attaching to a process.
DidAttach()70b9c1b51eSKate Stone void DynamicLoaderDarwin::DidAttach() {
715fe4d141SJason Molenda   PrivateInitialize(m_process);
725fe4d141SJason Molenda   DoInitialImageFetch();
735fe4d141SJason Molenda   SetNotificationBreakpoint();
745fe4d141SJason Molenda }
755fe4d141SJason Molenda 
765fe4d141SJason Molenda /// Called after attaching a process.
775fe4d141SJason Molenda ///
785fe4d141SJason Molenda /// Allow DynamicLoader plug-ins to execute some code after
795fe4d141SJason Molenda /// attaching to a process.
DidLaunch()80b9c1b51eSKate Stone void DynamicLoaderDarwin::DidLaunch() {
815fe4d141SJason Molenda   PrivateInitialize(m_process);
825fe4d141SJason Molenda   DoInitialImageFetch();
835fe4d141SJason Molenda   SetNotificationBreakpoint();
845fe4d141SJason Molenda }
855fe4d141SJason Molenda 
865fe4d141SJason Molenda // Clear out the state of this class.
Clear(bool clear_process)87b9c1b51eSKate Stone void DynamicLoaderDarwin::Clear(bool clear_process) {
885fe4d141SJason Molenda   std::lock_guard<std::recursive_mutex> guard(m_mutex);
895fe4d141SJason Molenda   if (clear_process)
90248a1305SKonrad Kleine     m_process = nullptr;
915fe4d141SJason Molenda   m_dyld_image_infos.clear();
925fe4d141SJason Molenda   m_dyld_image_infos_stop_id = UINT32_MAX;
935fe4d141SJason Molenda   m_dyld.Clear(false);
945fe4d141SJason Molenda }
955fe4d141SJason Molenda 
FindTargetModuleForImageInfo(ImageInfo & image_info,bool can_create,bool * did_create_ptr)96b9c1b51eSKate Stone ModuleSP DynamicLoaderDarwin::FindTargetModuleForImageInfo(
97b9c1b51eSKate Stone     ImageInfo &image_info, bool can_create, bool *did_create_ptr) {
985fe4d141SJason Molenda   if (did_create_ptr)
995fe4d141SJason Molenda     *did_create_ptr = false;
1005fe4d141SJason Molenda 
1015fe4d141SJason Molenda   Target &target = m_process->GetTarget();
1025fe4d141SJason Molenda   const ModuleList &target_images = target.GetImages();
1035fe4d141SJason Molenda   ModuleSpec module_spec(image_info.file_spec);
1045fe4d141SJason Molenda   module_spec.GetUUID() = image_info.uuid;
10524610611SAdrian Prantl 
10624610611SAdrian Prantl   // macCatalyst support: Request matching os/environment.
10724610611SAdrian Prantl   {
10824610611SAdrian Prantl     auto &target_triple = target.GetArchitecture().GetTriple();
10924610611SAdrian Prantl     if (target_triple.getOS() == llvm::Triple::IOS &&
11024610611SAdrian Prantl         target_triple.getEnvironment() == llvm::Triple::MacABI) {
11124610611SAdrian Prantl       // Request the macCatalyst variant of frameworks that have both
11224610611SAdrian Prantl       // a PLATFORM_MACOS and a PLATFORM_MACCATALYST load command.
11324610611SAdrian Prantl       module_spec.GetArchitecture() = ArchSpec(target_triple);
11424610611SAdrian Prantl     }
11524610611SAdrian Prantl   }
11624610611SAdrian Prantl 
1175fe4d141SJason Molenda   ModuleSP module_sp(target_images.FindFirstModule(module_spec));
1185fe4d141SJason Molenda 
119b9c1b51eSKate Stone   if (module_sp && !module_spec.GetUUID().IsValid() &&
120b9c1b51eSKate Stone       !module_sp->GetUUID().IsValid()) {
12105097246SAdrian Prantl     // No UUID, we must rely upon the cached module modification time and the
12205097246SAdrian Prantl     // modification time of the file on disk
123b9c1b51eSKate Stone     if (module_sp->GetModificationTime() !=
12446376966SJonas Devlieghere         FileSystem::Instance().GetModificationTime(module_sp->GetFileSpec()))
1255fe4d141SJason Molenda       module_sp.reset();
1265fe4d141SJason Molenda   }
1275fe4d141SJason Molenda 
1288113a8bbSFred Riss   if (module_sp || !can_create)
1298113a8bbSFred Riss     return module_sp;
1308113a8bbSFred Riss 
1318113a8bbSFred Riss   if (HostInfo::GetArchitecture().IsCompatibleMatch(target.GetArchitecture())) {
1328113a8bbSFred Riss     // When debugging on the host, we are most likely using the same shared
1338113a8bbSFred Riss     // cache as our inferior. The dylibs from the shared cache might not
1348113a8bbSFred Riss     // exist on the filesystem, so let's use the images in our own memory
1358113a8bbSFred Riss     // to create the modules.
1368113a8bbSFred Riss     // Check if the requested image is in our shared cache.
1378113a8bbSFred Riss     SharedCacheImageInfo image_info =
1388113a8bbSFred Riss         HostInfo::GetSharedCacheImageInfo(module_spec.GetFileSpec().GetPath());
1398113a8bbSFred Riss 
1408113a8bbSFred Riss     // If we found it and it has the correct UUID, let's proceed with
1418113a8bbSFred Riss     // creating a module from the memory contents.
1428113a8bbSFred Riss     if (image_info.uuid &&
1438113a8bbSFred Riss         (!module_spec.GetUUID() || module_spec.GetUUID() == image_info.uuid)) {
1448113a8bbSFred Riss       ModuleSpec shared_cache_spec(module_spec.GetFileSpec(), image_info.uuid,
1458113a8bbSFred Riss                                    image_info.data_sp);
1468113a8bbSFred Riss       module_sp =
1478113a8bbSFred Riss           target.GetOrCreateModule(shared_cache_spec, false /* notify */);
1488113a8bbSFred Riss     }
1498113a8bbSFred Riss   }
1501724a179SJason Molenda   // We'll call Target::ModulesDidLoad after all the modules have been
1511724a179SJason Molenda   // added to the target, don't let it be called for every one.
1528113a8bbSFred Riss   if (!module_sp)
1531724a179SJason Molenda     module_sp = target.GetOrCreateModule(module_spec, false /* notify */);
154248a1305SKonrad Kleine   if (!module_sp || module_sp->GetObjectFile() == nullptr)
155b9c1b51eSKate Stone     module_sp = m_process->ReadModuleFromMemory(image_info.file_spec,
156b9c1b51eSKate Stone                                                 image_info.address);
1575fe4d141SJason Molenda 
1585fe4d141SJason Molenda   if (did_create_ptr)
1595fe4d141SJason Molenda     *did_create_ptr = (bool)module_sp;
1608113a8bbSFred Riss 
1615fe4d141SJason Molenda   return module_sp;
1625fe4d141SJason Molenda }
1635fe4d141SJason Molenda 
UnloadImages(const std::vector<lldb::addr_t> & solib_addresses)164b9c1b51eSKate Stone void DynamicLoaderDarwin::UnloadImages(
165b9c1b51eSKate Stone     const std::vector<lldb::addr_t> &solib_addresses) {
1665fe4d141SJason Molenda   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1675fe4d141SJason Molenda   if (m_process->GetStopID() == m_dyld_image_infos_stop_id)
1685fe4d141SJason Molenda     return;
1695fe4d141SJason Molenda 
170a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::DynamicLoader);
1715fe4d141SJason Molenda   Target &target = m_process->GetTarget();
17263e5fb76SJonas Devlieghere   LLDB_LOGF(log, "Removing %" PRId64 " modules.",
173b9c1b51eSKate Stone             (uint64_t)solib_addresses.size());
1745fe4d141SJason Molenda 
1755fe4d141SJason Molenda   ModuleList unloaded_module_list;
1765fe4d141SJason Molenda 
177b9c1b51eSKate Stone   for (addr_t solib_addr : solib_addresses) {
1785fe4d141SJason Molenda     Address header;
179b9c1b51eSKate Stone     if (header.SetLoadAddress(solib_addr, &target)) {
180b9c1b51eSKate Stone       if (header.GetOffset() == 0) {
1815fe4d141SJason Molenda         ModuleSP module_to_remove(header.GetModule());
182b9c1b51eSKate Stone         if (module_to_remove.get()) {
18363e5fb76SJonas Devlieghere           LLDB_LOGF(log, "Removing module at address 0x%" PRIx64, solib_addr);
1845fe4d141SJason Molenda           // remove the sections from the Target
1855fe4d141SJason Molenda           UnloadSections(module_to_remove);
1865fe4d141SJason Molenda           // add this to the list of modules to remove
1875fe4d141SJason Molenda           unloaded_module_list.AppendIfNeeded(module_to_remove);
1885fe4d141SJason Molenda           // remove the entry from the m_dyld_image_infos
1895fe4d141SJason Molenda           ImageInfo::collection::iterator pos, end = m_dyld_image_infos.end();
190b9c1b51eSKate Stone           for (pos = m_dyld_image_infos.begin(); pos != end; pos++) {
191b9c1b51eSKate Stone             if (solib_addr == (*pos).address) {
1925fe4d141SJason Molenda               m_dyld_image_infos.erase(pos);
1935fe4d141SJason Molenda               break;
1945fe4d141SJason Molenda             }
1955fe4d141SJason Molenda           }
1965fe4d141SJason Molenda         }
1975fe4d141SJason Molenda       }
1985fe4d141SJason Molenda     }
1995fe4d141SJason Molenda   }
2005fe4d141SJason Molenda 
201b9c1b51eSKate Stone   if (unloaded_module_list.GetSize() > 0) {
202b9c1b51eSKate Stone     if (log) {
2035fe4d141SJason Molenda       log->PutCString("Unloaded:");
204b9c1b51eSKate Stone       unloaded_module_list.LogUUIDAndPaths(
205b9c1b51eSKate Stone           log, "DynamicLoaderDarwin::UnloadModules");
2065fe4d141SJason Molenda     }
2075fe4d141SJason Molenda     m_process->GetTarget().GetImages().Remove(unloaded_module_list);
2085fe4d141SJason Molenda     m_dyld_image_infos_stop_id = m_process->GetStopID();
2095fe4d141SJason Molenda   }
2105fe4d141SJason Molenda }
2115fe4d141SJason Molenda 
UnloadAllImages()212b9c1b51eSKate Stone void DynamicLoaderDarwin::UnloadAllImages() {
213a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::DynamicLoader);
2149ab5dc24SJason Molenda   ModuleList unloaded_modules_list;
2159ab5dc24SJason Molenda 
2169ab5dc24SJason Molenda   Target &target = m_process->GetTarget();
2179ab5dc24SJason Molenda   const ModuleList &target_modules = target.GetImages();
2189ab5dc24SJason Molenda   std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
2199ab5dc24SJason Molenda 
2209ab5dc24SJason Molenda   ModuleSP dyld_sp(GetDYLDModule());
221f2e05855SJonas Devlieghere   for (ModuleSP module_sp : target_modules.Modules()) {
222b9c1b51eSKate Stone     // Don't remove dyld - else we'll lose our breakpoint notifying us about
22305097246SAdrian Prantl     // libraries being re-loaded...
224f2e05855SJonas Devlieghere     if (module_sp && module_sp != dyld_sp) {
2259ab5dc24SJason Molenda       UnloadSections(module_sp);
2269ab5dc24SJason Molenda       unloaded_modules_list.Append(module_sp);
2279ab5dc24SJason Molenda     }
2289ab5dc24SJason Molenda   }
2299ab5dc24SJason Molenda 
230b9c1b51eSKate Stone   if (unloaded_modules_list.GetSize() != 0) {
231b9c1b51eSKate Stone     if (log) {
2329ab5dc24SJason Molenda       log->PutCString("Unloaded:");
233b9c1b51eSKate Stone       unloaded_modules_list.LogUUIDAndPaths(
234b9c1b51eSKate Stone           log, "DynamicLoaderDarwin::UnloadAllImages");
2359ab5dc24SJason Molenda     }
2369ab5dc24SJason Molenda     target.GetImages().Remove(unloaded_modules_list);
2379ab5dc24SJason Molenda     m_dyld_image_infos.clear();
2389ab5dc24SJason Molenda     m_dyld_image_infos_stop_id = m_process->GetStopID();
2399ab5dc24SJason Molenda   }
2409ab5dc24SJason Molenda }
2419ab5dc24SJason Molenda 
24205097246SAdrian Prantl // Update the load addresses for all segments in MODULE using the updated INFO
24305097246SAdrian Prantl // that is passed in.
UpdateImageLoadAddress(Module * module,ImageInfo & info)244b9c1b51eSKate Stone bool DynamicLoaderDarwin::UpdateImageLoadAddress(Module *module,
245b9c1b51eSKate Stone                                                  ImageInfo &info) {
2465fe4d141SJason Molenda   bool changed = false;
247b9c1b51eSKate Stone   if (module) {
2485fe4d141SJason Molenda     ObjectFile *image_object_file = module->GetObjectFile();
249b9c1b51eSKate Stone     if (image_object_file) {
2505fe4d141SJason Molenda       SectionList *section_list = image_object_file->GetSectionList();
251b9c1b51eSKate Stone       if (section_list) {
2525fe4d141SJason Molenda         std::vector<uint32_t> inaccessible_segment_indexes;
25305097246SAdrian Prantl         // We now know the slide amount, so go through all sections and update
25405097246SAdrian Prantl         // the load addresses with the correct values.
2555fe4d141SJason Molenda         const size_t num_segments = info.segments.size();
256b9c1b51eSKate Stone         for (size_t i = 0; i < num_segments; ++i) {
25705097246SAdrian Prantl           // Only load a segment if it has protections. Things like __PAGEZERO
25805097246SAdrian Prantl           // don't have any protections, and they shouldn't be slid
259b9c1b51eSKate Stone           SectionSP section_sp(
260b9c1b51eSKate Stone               section_list->FindSectionByName(info.segments[i].name));
2615fe4d141SJason Molenda 
262b9c1b51eSKate Stone           if (info.segments[i].maxprot == 0) {
2635fe4d141SJason Molenda             inaccessible_segment_indexes.push_back(i);
264b9c1b51eSKate Stone           } else {
265b9c1b51eSKate Stone             const addr_t new_section_load_addr =
266b9c1b51eSKate Stone                 info.segments[i].vmaddr + info.slide;
2675fe4d141SJason Molenda             static ConstString g_section_name_LINKEDIT("__LINKEDIT");
2685fe4d141SJason Molenda 
269b9c1b51eSKate Stone             if (section_sp) {
27005097246SAdrian Prantl               // __LINKEDIT sections from files in the shared cache can overlap
27105097246SAdrian Prantl               // so check to see what the segment name is and pass "false" so
27205097246SAdrian Prantl               // we don't warn of overlapping "Section" objects, and "true" for
27305097246SAdrian Prantl               // all other sections.
274b9c1b51eSKate Stone               const bool warn_multiple =
275b9c1b51eSKate Stone                   section_sp->GetName() != g_section_name_LINKEDIT;
2765fe4d141SJason Molenda 
277b9c1b51eSKate Stone               changed = m_process->GetTarget().SetSectionLoadAddress(
278b9c1b51eSKate Stone                   section_sp, new_section_load_addr, warn_multiple);
2795fe4d141SJason Molenda             }
2805fe4d141SJason Molenda           }
2815fe4d141SJason Molenda         }
2825fe4d141SJason Molenda 
28305097246SAdrian Prantl         // If the loaded the file (it changed) and we have segments that are
28405097246SAdrian Prantl         // not readable or writeable, add them to the invalid memory region
28505097246SAdrian Prantl         // cache for the process. This will typically only be the __PAGEZERO
28605097246SAdrian Prantl         // segment in the main executable. We might be able to apply this more
28705097246SAdrian Prantl         // generally to more sections that have no protections in the future,
28805097246SAdrian Prantl         // but for now we are going to just do __PAGEZERO.
289b9c1b51eSKate Stone         if (changed && !inaccessible_segment_indexes.empty()) {
290b9c1b51eSKate Stone           for (uint32_t i = 0; i < inaccessible_segment_indexes.size(); ++i) {
2915fe4d141SJason Molenda             const uint32_t seg_idx = inaccessible_segment_indexes[i];
292b9c1b51eSKate Stone             SectionSP section_sp(
293b9c1b51eSKate Stone                 section_list->FindSectionByName(info.segments[seg_idx].name));
2945fe4d141SJason Molenda 
295b9c1b51eSKate Stone             if (section_sp) {
2965fe4d141SJason Molenda               static ConstString g_pagezero_section_name("__PAGEZERO");
297b9c1b51eSKate Stone               if (g_pagezero_section_name == section_sp->GetName()) {
2985fe4d141SJason Molenda                 // __PAGEZERO never slides...
2995fe4d141SJason Molenda                 const lldb::addr_t vmaddr = info.segments[seg_idx].vmaddr;
3005fe4d141SJason Molenda                 const lldb::addr_t vmsize = info.segments[seg_idx].vmsize;
3015fe4d141SJason Molenda                 Process::LoadRange pagezero_range(vmaddr, vmsize);
3025fe4d141SJason Molenda                 m_process->AddInvalidMemoryRegion(pagezero_range);
3035fe4d141SJason Molenda               }
3045fe4d141SJason Molenda             }
3055fe4d141SJason Molenda           }
3065fe4d141SJason Molenda         }
3075fe4d141SJason Molenda       }
3085fe4d141SJason Molenda     }
3095fe4d141SJason Molenda   }
3105fe4d141SJason Molenda   // We might have an in memory image that was loaded as soon as it was created
3115fe4d141SJason Molenda   if (info.load_stop_id == m_process->GetStopID())
3125fe4d141SJason Molenda     changed = true;
313b9c1b51eSKate Stone   else if (changed) {
3145fe4d141SJason Molenda     // Update the stop ID when this library was updated
3155fe4d141SJason Molenda     info.load_stop_id = m_process->GetStopID();
3165fe4d141SJason Molenda   }
3175fe4d141SJason Molenda   return changed;
3185fe4d141SJason Molenda }
3195fe4d141SJason Molenda 
3205fe4d141SJason Molenda // Unload the segments in MODULE using the INFO that is passed in.
UnloadModuleSections(Module * module,ImageInfo & info)321b9c1b51eSKate Stone bool DynamicLoaderDarwin::UnloadModuleSections(Module *module,
322b9c1b51eSKate Stone                                                ImageInfo &info) {
3235fe4d141SJason Molenda   bool changed = false;
324b9c1b51eSKate Stone   if (module) {
3255fe4d141SJason Molenda     ObjectFile *image_object_file = module->GetObjectFile();
326b9c1b51eSKate Stone     if (image_object_file) {
3275fe4d141SJason Molenda       SectionList *section_list = image_object_file->GetSectionList();
328b9c1b51eSKate Stone       if (section_list) {
3295fe4d141SJason Molenda         const size_t num_segments = info.segments.size();
330b9c1b51eSKate Stone         for (size_t i = 0; i < num_segments; ++i) {
331b9c1b51eSKate Stone           SectionSP section_sp(
332b9c1b51eSKate Stone               section_list->FindSectionByName(info.segments[i].name));
333b9c1b51eSKate Stone           if (section_sp) {
334b9c1b51eSKate Stone             const addr_t old_section_load_addr =
335b9c1b51eSKate Stone                 info.segments[i].vmaddr + info.slide;
336b9c1b51eSKate Stone             if (m_process->GetTarget().SetSectionUnloaded(
337b9c1b51eSKate Stone                     section_sp, old_section_load_addr))
3385fe4d141SJason Molenda               changed = true;
339b9c1b51eSKate Stone           } else {
34068793919SJonas Devlieghere             Debugger::ReportWarning(
34168793919SJonas Devlieghere                 llvm::formatv("unable to find and unload segment named "
34268793919SJonas Devlieghere                               "'{0}' in '{1}' in macosx dynamic loader plug-in",
3435fe4d141SJason Molenda                               info.segments[i].name.AsCString("<invalid>"),
34468793919SJonas Devlieghere                               image_object_file->GetFileSpec().GetPath()));
3455fe4d141SJason Molenda           }
3465fe4d141SJason Molenda         }
3475fe4d141SJason Molenda       }
3485fe4d141SJason Molenda     }
3495fe4d141SJason Molenda   }
3505fe4d141SJason Molenda   return changed;
3515fe4d141SJason Molenda }
3525fe4d141SJason Molenda 
353b9c1b51eSKate Stone // Given a JSON dictionary (from debugserver, most likely) of binary images
35405097246SAdrian Prantl // loaded in the inferior process, add the images to the ImageInfo collection.
3555fe4d141SJason Molenda 
JSONImageInformationIntoImageInfo(StructuredData::ObjectSP image_details,ImageInfo::collection & image_infos)356b9c1b51eSKate Stone bool DynamicLoaderDarwin::JSONImageInformationIntoImageInfo(
357b9c1b51eSKate Stone     StructuredData::ObjectSP image_details,
358b9c1b51eSKate Stone     ImageInfo::collection &image_infos) {
359b9c1b51eSKate Stone   StructuredData::ObjectSP images_sp =
360b9c1b51eSKate Stone       image_details->GetAsDictionary()->GetValueForKey("images");
3615fe4d141SJason Molenda   if (images_sp.get() == nullptr)
3625fe4d141SJason Molenda     return false;
3635fe4d141SJason Molenda 
3645fe4d141SJason Molenda   image_infos.resize(images_sp->GetAsArray()->GetSize());
3655fe4d141SJason Molenda 
366b9c1b51eSKate Stone   for (size_t i = 0; i < image_infos.size(); i++) {
367b9c1b51eSKate Stone     StructuredData::ObjectSP image_sp =
368b9c1b51eSKate Stone         images_sp->GetAsArray()->GetItemAtIndex(i);
3695fe4d141SJason Molenda     if (image_sp.get() == nullptr || image_sp->GetAsDictionary() == nullptr)
3705fe4d141SJason Molenda       return false;
3715fe4d141SJason Molenda     StructuredData::Dictionary *image = image_sp->GetAsDictionary();
372a6682a41SJonas Devlieghere     // clang-format off
373a6682a41SJonas Devlieghere     if (!image->HasKey("load_address") ||
374a6682a41SJonas Devlieghere         !image->HasKey("pathname") ||
375a6682a41SJonas Devlieghere         !image->HasKey("mod_date") ||
376a6682a41SJonas Devlieghere         !image->HasKey("mach_header") ||
377b9c1b51eSKate Stone         image->GetValueForKey("mach_header")->GetAsDictionary() == nullptr ||
378a6682a41SJonas Devlieghere         !image->HasKey("segments") ||
379b9c1b51eSKate Stone         image->GetValueForKey("segments")->GetAsArray() == nullptr ||
380a6682a41SJonas Devlieghere         !image->HasKey("uuid")) {
3815fe4d141SJason Molenda       return false;
3825fe4d141SJason Molenda     }
383a6682a41SJonas Devlieghere     // clang-format on
384b9c1b51eSKate Stone     image_infos[i].address =
385b9c1b51eSKate Stone         image->GetValueForKey("load_address")->GetAsInteger()->GetValue();
386b9c1b51eSKate Stone     image_infos[i].mod_date =
387b9c1b51eSKate Stone         image->GetValueForKey("mod_date")->GetAsInteger()->GetValue();
388b9c1b51eSKate Stone     image_infos[i].file_spec.SetFile(
3898f3be7a3SJonas Devlieghere         image->GetValueForKey("pathname")->GetAsString()->GetValue(),
390937348cdSJonas Devlieghere         FileSpec::Style::native);
3915fe4d141SJason Molenda 
392b9c1b51eSKate Stone     StructuredData::Dictionary *mh =
393b9c1b51eSKate Stone         image->GetValueForKey("mach_header")->GetAsDictionary();
394b9c1b51eSKate Stone     image_infos[i].header.magic =
395b9c1b51eSKate Stone         mh->GetValueForKey("magic")->GetAsInteger()->GetValue();
396b9c1b51eSKate Stone     image_infos[i].header.cputype =
397b9c1b51eSKate Stone         mh->GetValueForKey("cputype")->GetAsInteger()->GetValue();
398b9c1b51eSKate Stone     image_infos[i].header.cpusubtype =
399b9c1b51eSKate Stone         mh->GetValueForKey("cpusubtype")->GetAsInteger()->GetValue();
400b9c1b51eSKate Stone     image_infos[i].header.filetype =
401b9c1b51eSKate Stone         mh->GetValueForKey("filetype")->GetAsInteger()->GetValue();
4025fe4d141SJason Molenda 
403b9c1b51eSKate Stone     if (image->HasKey("min_version_os_name")) {
404adcd0268SBenjamin Kramer       std::string os_name =
405adcd0268SBenjamin Kramer           std::string(image->GetValueForKey("min_version_os_name")
406b9c1b51eSKate Stone                           ->GetAsString()
407adcd0268SBenjamin Kramer                           ->GetValue());
4089ab5dc24SJason Molenda       if (os_name == "macosx")
4099ab5dc24SJason Molenda         image_infos[i].os_type = llvm::Triple::MacOSX;
4109ab5dc24SJason Molenda       else if (os_name == "ios" || os_name == "iphoneos")
4119ab5dc24SJason Molenda         image_infos[i].os_type = llvm::Triple::IOS;
4129ab5dc24SJason Molenda       else if (os_name == "tvos")
4139ab5dc24SJason Molenda         image_infos[i].os_type = llvm::Triple::TvOS;
4149ab5dc24SJason Molenda       else if (os_name == "watchos")
4159ab5dc24SJason Molenda         image_infos[i].os_type = llvm::Triple::WatchOS;
41632762fd2SJason Molenda       // NEED_BRIDGEOS_TRIPLE else if (os_name == "bridgeos")
41732762fd2SJason Molenda       // NEED_BRIDGEOS_TRIPLE   image_infos[i].os_type = llvm::Triple::BridgeOS;
41824610611SAdrian Prantl       else if (os_name == "maccatalyst") {
41924610611SAdrian Prantl         image_infos[i].os_type = llvm::Triple::IOS;
42024610611SAdrian Prantl         image_infos[i].os_env = llvm::Triple::MacABI;
42133b696b5SAdrian Prantl       } else if (os_name == "iossimulator") {
42233b696b5SAdrian Prantl         image_infos[i].os_type = llvm::Triple::IOS;
42333b696b5SAdrian Prantl         image_infos[i].os_env = llvm::Triple::Simulator;
42433b696b5SAdrian Prantl       } else if (os_name == "tvossimulator") {
42533b696b5SAdrian Prantl         image_infos[i].os_type = llvm::Triple::TvOS;
42633b696b5SAdrian Prantl         image_infos[i].os_env = llvm::Triple::Simulator;
42733b696b5SAdrian Prantl       } else if (os_name == "watchossimulator") {
42833b696b5SAdrian Prantl         image_infos[i].os_type = llvm::Triple::WatchOS;
42933b696b5SAdrian Prantl         image_infos[i].os_env = llvm::Triple::Simulator;
43024610611SAdrian Prantl       }
4319ab5dc24SJason Molenda     }
432b9c1b51eSKate Stone     if (image->HasKey("min_version_os_sdk")) {
433b9c1b51eSKate Stone       image_infos[i].min_version_os_sdk =
434adcd0268SBenjamin Kramer           std::string(image->GetValueForKey("min_version_os_sdk")
435b9c1b51eSKate Stone                           ->GetAsString()
436adcd0268SBenjamin Kramer                           ->GetValue());
4379ab5dc24SJason Molenda     }
4389ab5dc24SJason Molenda 
439b9c1b51eSKate Stone     // Fields that aren't used by DynamicLoaderDarwin so debugserver doesn't
44005097246SAdrian Prantl     // currently send them in the reply.
4415fe4d141SJason Molenda 
4425fe4d141SJason Molenda     if (mh->HasKey("flags"))
443b9c1b51eSKate Stone       image_infos[i].header.flags =
444b9c1b51eSKate Stone           mh->GetValueForKey("flags")->GetAsInteger()->GetValue();
4455fe4d141SJason Molenda     else
4465fe4d141SJason Molenda       image_infos[i].header.flags = 0;
4475fe4d141SJason Molenda 
4485fe4d141SJason Molenda     if (mh->HasKey("ncmds"))
449b9c1b51eSKate Stone       image_infos[i].header.ncmds =
450b9c1b51eSKate Stone           mh->GetValueForKey("ncmds")->GetAsInteger()->GetValue();
4515fe4d141SJason Molenda     else
4525fe4d141SJason Molenda       image_infos[i].header.ncmds = 0;
4535fe4d141SJason Molenda 
4545fe4d141SJason Molenda     if (mh->HasKey("sizeofcmds"))
455b9c1b51eSKate Stone       image_infos[i].header.sizeofcmds =
456b9c1b51eSKate Stone           mh->GetValueForKey("sizeofcmds")->GetAsInteger()->GetValue();
4575fe4d141SJason Molenda     else
4585fe4d141SJason Molenda       image_infos[i].header.sizeofcmds = 0;
4595fe4d141SJason Molenda 
460b9c1b51eSKate Stone     StructuredData::Array *segments =
461b9c1b51eSKate Stone         image->GetValueForKey("segments")->GetAsArray();
4625fe4d141SJason Molenda     uint32_t segcount = segments->GetSize();
463b9c1b51eSKate Stone     for (size_t j = 0; j < segcount; j++) {
4645fe4d141SJason Molenda       Segment segment;
465b9c1b51eSKate Stone       StructuredData::Dictionary *seg =
466b9c1b51eSKate Stone           segments->GetItemAtIndex(j)->GetAsDictionary();
4672833321fSZachary Turner       segment.name =
4682833321fSZachary Turner           ConstString(seg->GetValueForKey("name")->GetAsString()->GetValue());
469b9c1b51eSKate Stone       segment.vmaddr =
470b9c1b51eSKate Stone           seg->GetValueForKey("vmaddr")->GetAsInteger()->GetValue();
471b9c1b51eSKate Stone       segment.vmsize =
472b9c1b51eSKate Stone           seg->GetValueForKey("vmsize")->GetAsInteger()->GetValue();
473b9c1b51eSKate Stone       segment.fileoff =
474b9c1b51eSKate Stone           seg->GetValueForKey("fileoff")->GetAsInteger()->GetValue();
475b9c1b51eSKate Stone       segment.filesize =
476b9c1b51eSKate Stone           seg->GetValueForKey("filesize")->GetAsInteger()->GetValue();
477b9c1b51eSKate Stone       segment.maxprot =
478b9c1b51eSKate Stone           seg->GetValueForKey("maxprot")->GetAsInteger()->GetValue();
4795fe4d141SJason Molenda 
480b9c1b51eSKate Stone       // Fields that aren't used by DynamicLoaderDarwin so debugserver doesn't
48105097246SAdrian Prantl       // currently send them in the reply.
4825fe4d141SJason Molenda 
4835fe4d141SJason Molenda       if (seg->HasKey("initprot"))
484b9c1b51eSKate Stone         segment.initprot =
485b9c1b51eSKate Stone             seg->GetValueForKey("initprot")->GetAsInteger()->GetValue();
4865fe4d141SJason Molenda       else
4875fe4d141SJason Molenda         segment.initprot = 0;
4885fe4d141SJason Molenda 
4895fe4d141SJason Molenda       if (seg->HasKey("flags"))
490b9c1b51eSKate Stone         segment.flags =
491b9c1b51eSKate Stone             seg->GetValueForKey("flags")->GetAsInteger()->GetValue();
4925fe4d141SJason Molenda       else
4935fe4d141SJason Molenda         segment.flags = 0;
4945fe4d141SJason Molenda 
4955fe4d141SJason Molenda       if (seg->HasKey("nsects"))
496b9c1b51eSKate Stone         segment.nsects =
497b9c1b51eSKate Stone             seg->GetValueForKey("nsects")->GetAsInteger()->GetValue();
4985fe4d141SJason Molenda       else
4995fe4d141SJason Molenda         segment.nsects = 0;
5005fe4d141SJason Molenda 
5015fe4d141SJason Molenda       image_infos[i].segments.push_back(segment);
5025fe4d141SJason Molenda     }
5035fe4d141SJason Molenda 
504f3ecbfc1SJim Ingham     image_infos[i].uuid.SetFromOptionalStringRef(
5052833321fSZachary Turner         image->GetValueForKey("uuid")->GetAsString()->GetValue());
5065fe4d141SJason Molenda 
50705097246SAdrian Prantl     // All sections listed in the dyld image info structure will all either be
50805097246SAdrian Prantl     // fixed up already, or they will all be off by a single slide amount that
50905097246SAdrian Prantl     // is determined by finding the first segment that is at file offset zero
51005097246SAdrian Prantl     // which also has bytes (a file size that is greater than zero) in the
51105097246SAdrian Prantl     // object file.
5125fe4d141SJason Molenda 
5135fe4d141SJason Molenda     // Determine the slide amount (if any)
5145fe4d141SJason Molenda     const size_t num_sections = image_infos[i].segments.size();
515b9c1b51eSKate Stone     for (size_t k = 0; k < num_sections; ++k) {
51605097246SAdrian Prantl       // Iterate through the object file sections to find the first section
51705097246SAdrian Prantl       // that starts of file offset zero and that has bytes in the file...
518b9c1b51eSKate Stone       if ((image_infos[i].segments[k].fileoff == 0 &&
519b9c1b51eSKate Stone            image_infos[i].segments[k].filesize > 0) ||
52005cfdb0eSRaphael Isemann           (image_infos[i].segments[k].name == "__TEXT")) {
521b9c1b51eSKate Stone         image_infos[i].slide =
522b9c1b51eSKate Stone             image_infos[i].address - image_infos[i].segments[k].vmaddr;
52305097246SAdrian Prantl         // We have found the slide amount, so we can exit this for loop.
5245fe4d141SJason Molenda         break;
5255fe4d141SJason Molenda       }
5265fe4d141SJason Molenda     }
5275fe4d141SJason Molenda   }
5285fe4d141SJason Molenda 
5295fe4d141SJason Molenda   return true;
5305fe4d141SJason Molenda }
5315fe4d141SJason Molenda 
UpdateSpecialBinariesFromNewImageInfos(ImageInfo::collection & image_infos)532b9c1b51eSKate Stone void DynamicLoaderDarwin::UpdateSpecialBinariesFromNewImageInfos(
533b9c1b51eSKate Stone     ImageInfo::collection &image_infos) {
5349ab5dc24SJason Molenda   uint32_t exe_idx = UINT32_MAX;
5359ab5dc24SJason Molenda   uint32_t dyld_idx = UINT32_MAX;
5369ab5dc24SJason Molenda   Target &target = m_process->GetTarget();
537a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::DynamicLoader);
5389ab5dc24SJason Molenda   ConstString g_dyld_sim_filename("dyld_sim");
5399ab5dc24SJason Molenda 
5409ab5dc24SJason Molenda   ArchSpec target_arch = target.GetArchitecture();
5415fe4d141SJason Molenda   const size_t image_infos_size = image_infos.size();
542b9c1b51eSKate Stone   for (size_t i = 0; i < image_infos_size; i++) {
543b9c1b51eSKate Stone     if (image_infos[i].header.filetype == llvm::MachO::MH_DYLINKER) {
544fddafa11SJason Molenda       // In a "simulator" process we will have two dyld modules --
54532762fd2SJason Molenda       // a "dyld" that we want to keep track of, and a "dyld_sim" which
546fddafa11SJason Molenda       // we don't need to keep track of here.  dyld_sim will have a non-macosx
547fddafa11SJason Molenda       // OS.
548fddafa11SJason Molenda       if (target_arch.GetTriple().getEnvironment() == llvm::Triple::Simulator &&
549fddafa11SJason Molenda           image_infos[i].os_type != llvm::Triple::OSType::MacOSX) {
550fddafa11SJason Molenda         continue;
551fddafa11SJason Molenda       }
5529ab5dc24SJason Molenda 
553b9c1b51eSKate Stone       dyld_idx = i;
554b9c1b51eSKate Stone     }
555fddafa11SJason Molenda     if (image_infos[i].header.filetype == llvm::MachO::MH_EXECUTE) {
5569ab5dc24SJason Molenda       exe_idx = i;
5579ab5dc24SJason Molenda     }
5589ab5dc24SJason Molenda   }
5599ab5dc24SJason Molenda 
56016926115SRaphael Isemann   // Set the target executable if we haven't found one so far.
56116926115SRaphael Isemann   if (exe_idx != UINT32_MAX && !target.GetExecutableModule()) {
5629ab5dc24SJason Molenda     const bool can_create = true;
563248a1305SKonrad Kleine     ModuleSP exe_module_sp(FindTargetModuleForImageInfo(image_infos[exe_idx],
564248a1305SKonrad Kleine                                                         can_create, nullptr));
565b9c1b51eSKate Stone     if (exe_module_sp) {
56663e5fb76SJonas Devlieghere       LLDB_LOGF(log, "Found executable module: %s",
567b9c1b51eSKate Stone                 exe_module_sp->GetFileSpec().GetPath().c_str());
5689ab5dc24SJason Molenda       target.GetImages().AppendIfNeeded(exe_module_sp);
5699ab5dc24SJason Molenda       UpdateImageLoadAddress(exe_module_sp.get(), image_infos[exe_idx]);
570b9c1b51eSKate Stone       if (exe_module_sp.get() != target.GetExecutableModulePointer()) {
571f9a07e9fSJonas Devlieghere         target.SetExecutableModule(exe_module_sp, eLoadDependentsNo);
5729ab5dc24SJason Molenda       }
5739ab5dc24SJason Molenda     }
5749ab5dc24SJason Molenda   }
5759ab5dc24SJason Molenda 
576b9c1b51eSKate Stone   if (dyld_idx != UINT32_MAX) {
5779ab5dc24SJason Molenda     const bool can_create = true;
578248a1305SKonrad Kleine     ModuleSP dyld_sp = FindTargetModuleForImageInfo(image_infos[dyld_idx],
579248a1305SKonrad Kleine                                                     can_create, nullptr);
580b9c1b51eSKate Stone     if (dyld_sp.get()) {
58163e5fb76SJonas Devlieghere       LLDB_LOGF(log, "Found dyld module: %s",
582b9c1b51eSKate Stone                 dyld_sp->GetFileSpec().GetPath().c_str());
5839ab5dc24SJason Molenda       target.GetImages().AppendIfNeeded(dyld_sp);
5849ab5dc24SJason Molenda       UpdateImageLoadAddress(dyld_sp.get(), image_infos[dyld_idx]);
5859ab5dc24SJason Molenda       SetDYLDModule(dyld_sp);
5865fe4d141SJason Molenda     }
5875fe4d141SJason Molenda   }
5885fe4d141SJason Molenda }
5895fe4d141SJason Molenda 
UpdateDYLDImageInfoFromNewImageInfo(ImageInfo & image_info)590b9c1b51eSKate Stone void DynamicLoaderDarwin::UpdateDYLDImageInfoFromNewImageInfo(
591b9c1b51eSKate Stone     ImageInfo &image_info) {
592b9c1b51eSKate Stone   if (image_info.header.filetype == llvm::MachO::MH_DYLINKER) {
5935fe4d141SJason Molenda     const bool can_create = true;
594b9c1b51eSKate Stone     ModuleSP dyld_sp =
595248a1305SKonrad Kleine         FindTargetModuleForImageInfo(image_info, can_create, nullptr);
596b9c1b51eSKate Stone     if (dyld_sp.get()) {
5975fe4d141SJason Molenda       Target &target = m_process->GetTarget();
5985fe4d141SJason Molenda       target.GetImages().AppendIfNeeded(dyld_sp);
5995fe4d141SJason Molenda       UpdateImageLoadAddress(dyld_sp.get(), image_info);
6005fe4d141SJason Molenda       SetDYLDModule(dyld_sp);
6015fe4d141SJason Molenda     }
6025fe4d141SJason Molenda   }
6035fe4d141SJason Molenda }
6045fe4d141SJason Molenda 
SetDYLDModule(lldb::ModuleSP & dyld_module_sp)605b9c1b51eSKate Stone void DynamicLoaderDarwin::SetDYLDModule(lldb::ModuleSP &dyld_module_sp) {
6065fe4d141SJason Molenda   m_dyld_module_wp = dyld_module_sp;
6075fe4d141SJason Molenda }
6085fe4d141SJason Molenda 
GetDYLDModule()609b9c1b51eSKate Stone ModuleSP DynamicLoaderDarwin::GetDYLDModule() {
6105fe4d141SJason Molenda   ModuleSP dyld_sp(m_dyld_module_wp.lock());
6115fe4d141SJason Molenda   return dyld_sp;
6125fe4d141SJason Molenda }
6135fe4d141SJason Molenda 
ClearDYLDModule()6148d5a6007SJason Molenda void DynamicLoaderDarwin::ClearDYLDModule() { m_dyld_module_wp.reset(); }
6158d5a6007SJason Molenda 
AddModulesUsingImageInfos(ImageInfo::collection & image_infos)616b9c1b51eSKate Stone bool DynamicLoaderDarwin::AddModulesUsingImageInfos(
617b9c1b51eSKate Stone     ImageInfo::collection &image_infos) {
6185fe4d141SJason Molenda   std::lock_guard<std::recursive_mutex> guard(m_mutex);
6195fe4d141SJason Molenda   // Now add these images to the main list.
6205fe4d141SJason Molenda   ModuleList loaded_module_list;
621a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::DynamicLoader);
6225fe4d141SJason Molenda   Target &target = m_process->GetTarget();
6235fe4d141SJason Molenda   ModuleList &target_images = target.GetImages();
6245fe4d141SJason Molenda 
625b9c1b51eSKate Stone   for (uint32_t idx = 0; idx < image_infos.size(); ++idx) {
626b9c1b51eSKate Stone     if (log) {
62763e5fb76SJonas Devlieghere       LLDB_LOGF(log, "Adding new image at address=0x%16.16" PRIx64 ".",
628b9c1b51eSKate Stone                 image_infos[idx].address);
6295fe4d141SJason Molenda       image_infos[idx].PutToLog(log);
6305fe4d141SJason Molenda     }
6315fe4d141SJason Molenda 
6325fe4d141SJason Molenda     m_dyld_image_infos.push_back(image_infos[idx]);
6335fe4d141SJason Molenda 
634b9c1b51eSKate Stone     ModuleSP image_module_sp(
635248a1305SKonrad Kleine         FindTargetModuleForImageInfo(image_infos[idx], true, nullptr));
6365fe4d141SJason Molenda 
637b9c1b51eSKate Stone     if (image_module_sp) {
6385fe4d141SJason Molenda       ObjectFile *objfile = image_module_sp->GetObjectFile();
639b9c1b51eSKate Stone       if (objfile) {
6405fe4d141SJason Molenda         SectionList *sections = objfile->GetSectionList();
641b9c1b51eSKate Stone         if (sections) {
6425fe4d141SJason Molenda           ConstString commpage_dbstr("__commpage");
643b9c1b51eSKate Stone           Section *commpage_section =
644b9c1b51eSKate Stone               sections->FindSectionByName(commpage_dbstr).get();
645b9c1b51eSKate Stone           if (commpage_section) {
646b9c1b51eSKate Stone             ModuleSpec module_spec(objfile->GetFileSpec(),
647b9c1b51eSKate Stone                                    image_infos[idx].GetArchitecture());
6485fe4d141SJason Molenda             module_spec.GetObjectName() = commpage_dbstr;
649b9c1b51eSKate Stone             ModuleSP commpage_image_module_sp(
650b9c1b51eSKate Stone                 target_images.FindFirstModule(module_spec));
651b9c1b51eSKate Stone             if (!commpage_image_module_sp) {
652b9c1b51eSKate Stone               module_spec.SetObjectOffset(objfile->GetFileOffset() +
653b9c1b51eSKate Stone                                           commpage_section->GetFileOffset());
6545fe4d141SJason Molenda               module_spec.SetObjectSize(objfile->GetByteSize());
6551724a179SJason Molenda               commpage_image_module_sp = target.GetOrCreateModule(module_spec,
6561724a179SJason Molenda                                                                true /* notify */);
657b9c1b51eSKate Stone               if (!commpage_image_module_sp ||
658248a1305SKonrad Kleine                   commpage_image_module_sp->GetObjectFile() == nullptr) {
659b9c1b51eSKate Stone                 commpage_image_module_sp = m_process->ReadModuleFromMemory(
660b9c1b51eSKate Stone                     image_infos[idx].file_spec, image_infos[idx].address);
6615fe4d141SJason Molenda                 // Always load a memory image right away in the target in case
6625fe4d141SJason Molenda                 // we end up trying to read the symbol table from memory... The
6635fe4d141SJason Molenda                 // __LINKEDIT will need to be mapped so we can figure out where
6645fe4d141SJason Molenda                 // the symbol table bits are...
6655fe4d141SJason Molenda                 bool changed = false;
666b9c1b51eSKate Stone                 UpdateImageLoadAddress(commpage_image_module_sp.get(),
667b9c1b51eSKate Stone                                        image_infos[idx]);
6685fe4d141SJason Molenda                 target.GetImages().Append(commpage_image_module_sp);
669b9c1b51eSKate Stone                 if (changed) {
6705fe4d141SJason Molenda                   image_infos[idx].load_stop_id = m_process->GetStopID();
6715fe4d141SJason Molenda                   loaded_module_list.AppendIfNeeded(commpage_image_module_sp);
6725fe4d141SJason Molenda                 }
6735fe4d141SJason Molenda               }
6745fe4d141SJason Molenda             }
6755fe4d141SJason Molenda           }
6765fe4d141SJason Molenda         }
6775fe4d141SJason Molenda       }
6785fe4d141SJason Molenda 
67905097246SAdrian Prantl       // UpdateImageLoadAddress will return true if any segments change load
68005097246SAdrian Prantl       // address. We need to check this so we don't mention that all loaded
68105097246SAdrian Prantl       // shared libraries are newly loaded each time we hit out dyld breakpoint
68205097246SAdrian Prantl       // since dyld will list all shared libraries each time.
683b9c1b51eSKate Stone       if (UpdateImageLoadAddress(image_module_sp.get(), image_infos[idx])) {
6845fe4d141SJason Molenda         target_images.AppendIfNeeded(image_module_sp);
6855fe4d141SJason Molenda         loaded_module_list.AppendIfNeeded(image_module_sp);
6865fe4d141SJason Molenda       }
68724610611SAdrian Prantl 
688116b1033SAdrian Prantl       // To support macCatalyst and legacy iOS simulator,
689116b1033SAdrian Prantl       // update the module's platform with the DYLD info.
69024610611SAdrian Prantl       ArchSpec dyld_spec = image_infos[idx].GetArchitecture();
691116b1033SAdrian Prantl       auto &dyld_triple = dyld_spec.GetTriple();
692116b1033SAdrian Prantl       if ((dyld_triple.getEnvironment() == llvm::Triple::MacABI &&
693116b1033SAdrian Prantl            dyld_triple.getOS() == llvm::Triple::IOS) ||
694116b1033SAdrian Prantl           (dyld_triple.getEnvironment() == llvm::Triple::Simulator &&
695116b1033SAdrian Prantl            (dyld_triple.getOS() == llvm::Triple::IOS ||
696116b1033SAdrian Prantl             dyld_triple.getOS() == llvm::Triple::TvOS ||
697116b1033SAdrian Prantl             dyld_triple.getOS() == llvm::Triple::WatchOS)))
69824610611SAdrian Prantl         image_module_sp->MergeArchitecture(dyld_spec);
6995fe4d141SJason Molenda     }
7005fe4d141SJason Molenda   }
7015fe4d141SJason Molenda 
702b9c1b51eSKate Stone   if (loaded_module_list.GetSize() > 0) {
7035fe4d141SJason Molenda     if (log)
704b9c1b51eSKate Stone       loaded_module_list.LogUUIDAndPaths(log,
705b9c1b51eSKate Stone                                          "DynamicLoaderDarwin::ModulesDidLoad");
7065fe4d141SJason Molenda     m_process->GetTarget().ModulesDidLoad(loaded_module_list);
7075fe4d141SJason Molenda   }
7085fe4d141SJason Molenda   return true;
7095fe4d141SJason Molenda }
7105fe4d141SJason Molenda 
7115fe4d141SJason Molenda // On Mac OS X libobjc (the Objective-C runtime) has several critical dispatch
71205097246SAdrian Prantl // functions written in hand-written assembly, and also have hand-written
71305097246SAdrian Prantl // unwind information in the eh_frame section.  Normally we prefer analyzing
71405097246SAdrian Prantl // the assembly instructions of a currently executing frame to unwind from that
71505097246SAdrian Prantl // frame -- but on hand-written functions this profiling can fail.  We should
71605097246SAdrian Prantl // use the eh_frame instructions for these functions all the time.
7175fe4d141SJason Molenda //
7185fe4d141SJason Molenda // As an aside, it would be better if the eh_frame entries had a flag (or were
7195fe4d141SJason Molenda // extensible so they could have an Apple-specific flag) which indicates that
7205fe4d141SJason Molenda // the instructions are asynchronous -- accurate at every instruction, instead
7215fe4d141SJason Molenda // of our normal default assumption that they are not.
7225fe4d141SJason Molenda 
AlwaysRelyOnEHUnwindInfo(SymbolContext & sym_ctx)723b9c1b51eSKate Stone bool DynamicLoaderDarwin::AlwaysRelyOnEHUnwindInfo(SymbolContext &sym_ctx) {
7245fe4d141SJason Molenda   ModuleSP module_sp;
725b9c1b51eSKate Stone   if (sym_ctx.symbol) {
7265fe4d141SJason Molenda     module_sp = sym_ctx.symbol->GetAddressRef().GetModule();
7275fe4d141SJason Molenda   }
728248a1305SKonrad Kleine   if (module_sp.get() == nullptr && sym_ctx.function) {
729b9c1b51eSKate Stone     module_sp =
730b9c1b51eSKate Stone         sym_ctx.function->GetAddressRange().GetBaseAddress().GetModule();
7315fe4d141SJason Molenda   }
732248a1305SKonrad Kleine   if (module_sp.get() == nullptr)
7335fe4d141SJason Molenda     return false;
7345fe4d141SJason Molenda 
735e823bbe8SAlex Langford   ObjCLanguageRuntime *objc_runtime = ObjCLanguageRuntime::Get(*m_process);
736248a1305SKonrad Kleine   return objc_runtime != nullptr &&
737248a1305SKonrad Kleine          objc_runtime->IsModuleObjCLibrary(module_sp);
7385fe4d141SJason Molenda }
7395fe4d141SJason Molenda 
7405fe4d141SJason Molenda // Dump a Segment to the file handle provided.
PutToLog(Log * log,lldb::addr_t slide) const741b9c1b51eSKate Stone void DynamicLoaderDarwin::Segment::PutToLog(Log *log,
742b9c1b51eSKate Stone                                             lldb::addr_t slide) const {
743b9c1b51eSKate Stone   if (log) {
7445fe4d141SJason Molenda     if (slide == 0)
74563e5fb76SJonas Devlieghere       LLDB_LOGF(log, "\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ")",
746b9c1b51eSKate Stone                 name.AsCString(""), vmaddr + slide, vmaddr + slide + vmsize);
7475fe4d141SJason Molenda     else
74863e5fb76SJonas Devlieghere       LLDB_LOGF(log,
74963e5fb76SJonas Devlieghere                 "\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64
750b9c1b51eSKate Stone                 ") slide = 0x%" PRIx64,
751b9c1b51eSKate Stone                 name.AsCString(""), vmaddr + slide, vmaddr + slide + vmsize,
7525fe4d141SJason Molenda                 slide);
7535fe4d141SJason Molenda   }
7545fe4d141SJason Molenda }
7555fe4d141SJason Molenda 
GetArchitecture() const75624610611SAdrian Prantl lldb_private::ArchSpec DynamicLoaderDarwin::ImageInfo::GetArchitecture() const {
75724610611SAdrian Prantl   // Update the module's platform with the DYLD info.
75824610611SAdrian Prantl   lldb_private::ArchSpec arch_spec(lldb_private::eArchTypeMachO, header.cputype,
75924610611SAdrian Prantl                                    header.cpusubtype);
760116b1033SAdrian Prantl   if (os_env == llvm::Triple::MacABI && os_type == llvm::Triple::IOS) {
761116b1033SAdrian Prantl     llvm::Triple triple(llvm::Twine(arch_spec.GetArchitectureName()) +
762116b1033SAdrian Prantl                         "-apple-ios" + min_version_os_sdk + "-macabi");
76324610611SAdrian Prantl     ArchSpec maccatalyst_spec(triple);
76424610611SAdrian Prantl     if (arch_spec.IsCompatibleMatch(maccatalyst_spec))
76524610611SAdrian Prantl       arch_spec.MergeFrom(maccatalyst_spec);
76624610611SAdrian Prantl   }
767116b1033SAdrian Prantl   if (os_env == llvm::Triple::Simulator &&
768116b1033SAdrian Prantl       (os_type == llvm::Triple::IOS || os_type == llvm::Triple::TvOS ||
769116b1033SAdrian Prantl        os_type == llvm::Triple::WatchOS)) {
770116b1033SAdrian Prantl     llvm::Triple triple(llvm::Twine(arch_spec.GetArchitectureName()) +
771116b1033SAdrian Prantl                         "-apple-" + llvm::Triple::getOSTypeName(os_type) +
772116b1033SAdrian Prantl                         min_version_os_sdk + "-simulator");
773116b1033SAdrian Prantl     ArchSpec sim_spec(triple);
774116b1033SAdrian Prantl     if (arch_spec.IsCompatibleMatch(sim_spec))
775116b1033SAdrian Prantl       arch_spec.MergeFrom(sim_spec);
776116b1033SAdrian Prantl   }
77724610611SAdrian Prantl   return arch_spec;
77824610611SAdrian Prantl }
77924610611SAdrian Prantl 
7805fe4d141SJason Molenda const DynamicLoaderDarwin::Segment *
FindSegment(ConstString name) const7810e4c4821SAdrian Prantl DynamicLoaderDarwin::ImageInfo::FindSegment(ConstString name) const {
7825fe4d141SJason Molenda   const size_t num_segments = segments.size();
783b9c1b51eSKate Stone   for (size_t i = 0; i < num_segments; ++i) {
7845fe4d141SJason Molenda     if (segments[i].name == name)
7855fe4d141SJason Molenda       return &segments[i];
7865fe4d141SJason Molenda   }
787248a1305SKonrad Kleine   return nullptr;
7885fe4d141SJason Molenda }
7895fe4d141SJason Molenda 
7905fe4d141SJason Molenda // Dump an image info structure to the file handle provided.
PutToLog(Log * log) const791b9c1b51eSKate Stone void DynamicLoaderDarwin::ImageInfo::PutToLog(Log *log) const {
792fbb14285SPavel Labath   if (!log)
7935fe4d141SJason Molenda     return;
794b9c1b51eSKate Stone   if (address == LLDB_INVALID_ADDRESS) {
795fbb14285SPavel Labath     LLDB_LOG(log, "modtime={0:x+8} uuid={1} path='{2}' (UNLOADED)", mod_date,
796fbb14285SPavel Labath              uuid.GetAsString(), file_spec.GetPath());
797b9c1b51eSKate Stone   } else {
798fbb14285SPavel Labath     LLDB_LOG(log, "address={0:x+16} modtime={1:x+8} uuid={2} path='{3}'",
799fbb14285SPavel Labath              address, mod_date, uuid.GetAsString(), file_spec.GetPath());
8005fe4d141SJason Molenda     for (uint32_t i = 0; i < segments.size(); ++i)
8015fe4d141SJason Molenda       segments[i].PutToLog(log, slide);
8025fe4d141SJason Molenda   }
8035fe4d141SJason Molenda }
8045fe4d141SJason Molenda 
PrivateInitialize(Process * process)805b9c1b51eSKate Stone void DynamicLoaderDarwin::PrivateInitialize(Process *process) {
806b9c1b51eSKate Stone   DEBUG_PRINTF("DynamicLoaderDarwin::%s() process state = %s\n", __FUNCTION__,
807b9c1b51eSKate Stone                StateAsCString(m_process->GetState()));
8085fe4d141SJason Molenda   Clear(true);
8095fe4d141SJason Molenda   m_process = process;
8105fe4d141SJason Molenda   m_process->GetTarget().ClearAllLoadedSections();
8115fe4d141SJason Molenda }
8125fe4d141SJason Molenda 
8135fe4d141SJason Molenda // Member function that gets called when the process state changes.
PrivateProcessStateChanged(Process * process,StateType state)814b9c1b51eSKate Stone void DynamicLoaderDarwin::PrivateProcessStateChanged(Process *process,
815b9c1b51eSKate Stone                                                      StateType state) {
816b9c1b51eSKate Stone   DEBUG_PRINTF("DynamicLoaderDarwin::%s(%s)\n", __FUNCTION__,
817b9c1b51eSKate Stone                StateAsCString(state));
818b9c1b51eSKate Stone   switch (state) {
8195fe4d141SJason Molenda   case eStateConnected:
8205fe4d141SJason Molenda   case eStateAttaching:
8215fe4d141SJason Molenda   case eStateLaunching:
8225fe4d141SJason Molenda   case eStateInvalid:
8235fe4d141SJason Molenda   case eStateUnloaded:
8245fe4d141SJason Molenda   case eStateExited:
8255fe4d141SJason Molenda   case eStateDetached:
8265fe4d141SJason Molenda     Clear(false);
8275fe4d141SJason Molenda     break;
8285fe4d141SJason Molenda 
8295fe4d141SJason Molenda   case eStateStopped:
83005097246SAdrian Prantl     // Keep trying find dyld and set our notification breakpoint each time we
83105097246SAdrian Prantl     // stop until we succeed
832b9c1b51eSKate Stone     if (!DidSetNotificationBreakpoint() && m_process->IsAlive()) {
8335fe4d141SJason Molenda       if (NeedToDoInitialImageFetch())
8345fe4d141SJason Molenda         DoInitialImageFetch();
8355fe4d141SJason Molenda 
8365fe4d141SJason Molenda       SetNotificationBreakpoint();
8375fe4d141SJason Molenda     }
8385fe4d141SJason Molenda     break;
8395fe4d141SJason Molenda 
8405fe4d141SJason Molenda   case eStateRunning:
8415fe4d141SJason Molenda   case eStateStepping:
8425fe4d141SJason Molenda   case eStateCrashed:
8435fe4d141SJason Molenda   case eStateSuspended:
8445fe4d141SJason Molenda     break;
8455fe4d141SJason Molenda   }
8465fe4d141SJason Molenda }
8475fe4d141SJason Molenda 
8485fe4d141SJason Molenda ThreadPlanSP
GetStepThroughTrampolinePlan(Thread & thread,bool stop_others)849b9c1b51eSKate Stone DynamicLoaderDarwin::GetStepThroughTrampolinePlan(Thread &thread,
850b9c1b51eSKate Stone                                                   bool stop_others) {
8515fe4d141SJason Molenda   ThreadPlanSP thread_plan_sp;
8525fe4d141SJason Molenda   StackFrame *current_frame = thread.GetStackFrameAtIndex(0).get();
853b9c1b51eSKate Stone   const SymbolContext &current_context =
854b9c1b51eSKate Stone       current_frame->GetSymbolContext(eSymbolContextSymbol);
8555fe4d141SJason Molenda   Symbol *current_symbol = current_context.symbol;
856a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Step);
8575fe4d141SJason Molenda   TargetSP target_sp(thread.CalculateTarget());
8585fe4d141SJason Molenda 
859248a1305SKonrad Kleine   if (current_symbol != nullptr) {
8605fe4d141SJason Molenda     std::vector<Address> addresses;
8615fe4d141SJason Molenda 
862b9c1b51eSKate Stone     if (current_symbol->IsTrampoline()) {
86322b04487SAlex Langford       ConstString trampoline_name =
86422b04487SAlex Langford           current_symbol->GetMangled().GetName(Mangled::ePreferMangled);
8655fe4d141SJason Molenda 
866b9c1b51eSKate Stone       if (trampoline_name) {
8675fe4d141SJason Molenda         const ModuleList &images = target_sp->GetImages();
8685fe4d141SJason Molenda 
8695fe4d141SJason Molenda         SymbolContextList code_symbols;
870b9c1b51eSKate Stone         images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeCode,
871b9c1b51eSKate Stone                                           code_symbols);
8725fe4d141SJason Molenda         size_t num_code_symbols = code_symbols.GetSize();
8735fe4d141SJason Molenda 
874b9c1b51eSKate Stone         if (num_code_symbols > 0) {
875b9c1b51eSKate Stone           for (uint32_t i = 0; i < num_code_symbols; i++) {
8765fe4d141SJason Molenda             SymbolContext context;
8775fe4d141SJason Molenda             AddressRange addr_range;
878b9c1b51eSKate Stone             if (code_symbols.GetContextAtIndex(i, context)) {
879b9c1b51eSKate Stone               context.GetAddressRange(eSymbolContextEverything, 0, false,
880b9c1b51eSKate Stone                                       addr_range);
8815fe4d141SJason Molenda               addresses.push_back(addr_range.GetBaseAddress());
882b9c1b51eSKate Stone               if (log) {
883b9c1b51eSKate Stone                 addr_t load_addr =
884b9c1b51eSKate Stone                     addr_range.GetBaseAddress().GetLoadAddress(target_sp.get());
8855fe4d141SJason Molenda 
88663e5fb76SJonas Devlieghere                 LLDB_LOGF(log,
88763e5fb76SJonas Devlieghere                           "Found a trampoline target symbol at 0x%" PRIx64 ".",
888b9c1b51eSKate Stone                           load_addr);
8895fe4d141SJason Molenda               }
8905fe4d141SJason Molenda             }
8915fe4d141SJason Molenda           }
8925fe4d141SJason Molenda         }
8935fe4d141SJason Molenda 
8945fe4d141SJason Molenda         SymbolContextList reexported_symbols;
895b9c1b51eSKate Stone         images.FindSymbolsWithNameAndType(
896b9c1b51eSKate Stone             trampoline_name, eSymbolTypeReExported, reexported_symbols);
8975fe4d141SJason Molenda         size_t num_reexported_symbols = reexported_symbols.GetSize();
898b9c1b51eSKate Stone         if (num_reexported_symbols > 0) {
899b9c1b51eSKate Stone           for (uint32_t i = 0; i < num_reexported_symbols; i++) {
9005fe4d141SJason Molenda             SymbolContext context;
901b9c1b51eSKate Stone             if (reexported_symbols.GetContextAtIndex(i, context)) {
902b9c1b51eSKate Stone               if (context.symbol) {
903b9c1b51eSKate Stone                 Symbol *actual_symbol =
904b9c1b51eSKate Stone                     context.symbol->ResolveReExportedSymbol(*target_sp.get());
905b9c1b51eSKate Stone                 if (actual_symbol) {
906b9c1b51eSKate Stone                   const Address actual_symbol_addr =
907b9c1b51eSKate Stone                       actual_symbol->GetAddress();
908b9c1b51eSKate Stone                   if (actual_symbol_addr.IsValid()) {
9095fe4d141SJason Molenda                     addresses.push_back(actual_symbol_addr);
910b9c1b51eSKate Stone                     if (log) {
911b9c1b51eSKate Stone                       lldb::addr_t load_addr =
912b9c1b51eSKate Stone                           actual_symbol_addr.GetLoadAddress(target_sp.get());
91363e5fb76SJonas Devlieghere                       LLDB_LOGF(
91463e5fb76SJonas Devlieghere                           log,
915b9c1b51eSKate Stone                           "Found a re-exported symbol: %s at 0x%" PRIx64 ".",
9165fe4d141SJason Molenda                           actual_symbol->GetName().GetCString(), load_addr);
9175fe4d141SJason Molenda                     }
9185fe4d141SJason Molenda                   }
9195fe4d141SJason Molenda                 }
9205fe4d141SJason Molenda               }
9215fe4d141SJason Molenda             }
9225fe4d141SJason Molenda           }
9235fe4d141SJason Molenda         }
9245fe4d141SJason Molenda 
9255fe4d141SJason Molenda         SymbolContextList indirect_symbols;
926b9c1b51eSKate Stone         images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeResolver,
927b9c1b51eSKate Stone                                           indirect_symbols);
9285fe4d141SJason Molenda         size_t num_indirect_symbols = indirect_symbols.GetSize();
929b9c1b51eSKate Stone         if (num_indirect_symbols > 0) {
930b9c1b51eSKate Stone           for (uint32_t i = 0; i < num_indirect_symbols; i++) {
9315fe4d141SJason Molenda             SymbolContext context;
9325fe4d141SJason Molenda             AddressRange addr_range;
933b9c1b51eSKate Stone             if (indirect_symbols.GetContextAtIndex(i, context)) {
934b9c1b51eSKate Stone               context.GetAddressRange(eSymbolContextEverything, 0, false,
935b9c1b51eSKate Stone                                       addr_range);
9365fe4d141SJason Molenda               addresses.push_back(addr_range.GetBaseAddress());
937b9c1b51eSKate Stone               if (log) {
938b9c1b51eSKate Stone                 addr_t load_addr =
939b9c1b51eSKate Stone                     addr_range.GetBaseAddress().GetLoadAddress(target_sp.get());
9405fe4d141SJason Molenda 
94163e5fb76SJonas Devlieghere                 LLDB_LOGF(log,
94263e5fb76SJonas Devlieghere                           "Found an indirect target symbol at 0x%" PRIx64 ".",
943b9c1b51eSKate Stone                           load_addr);
9445fe4d141SJason Molenda               }
9455fe4d141SJason Molenda             }
9465fe4d141SJason Molenda           }
9475fe4d141SJason Molenda         }
9485fe4d141SJason Molenda       }
949b9c1b51eSKate Stone     } else if (current_symbol->GetType() == eSymbolTypeReExported) {
950b9c1b51eSKate Stone       // I am not sure we could ever end up stopped AT a re-exported symbol.
951b9c1b51eSKate Stone       // But just in case:
9525fe4d141SJason Molenda 
953b9c1b51eSKate Stone       const Symbol *actual_symbol =
954b9c1b51eSKate Stone           current_symbol->ResolveReExportedSymbol(*(target_sp.get()));
955b9c1b51eSKate Stone       if (actual_symbol) {
9565fe4d141SJason Molenda         Address target_addr(actual_symbol->GetAddress());
957b9c1b51eSKate Stone         if (target_addr.IsValid()) {
95863e5fb76SJonas Devlieghere           LLDB_LOGF(
95963e5fb76SJonas Devlieghere               log,
960b9c1b51eSKate Stone               "Found a re-exported symbol: %s pointing to: %s at 0x%" PRIx64
961b9c1b51eSKate Stone               ".",
9625fe4d141SJason Molenda               current_symbol->GetName().GetCString(),
9635fe4d141SJason Molenda               actual_symbol->GetName().GetCString(),
9645fe4d141SJason Molenda               target_addr.GetLoadAddress(target_sp.get()));
9655fe4d141SJason Molenda           addresses.push_back(target_addr.GetLoadAddress(target_sp.get()));
9665fe4d141SJason Molenda         }
9675fe4d141SJason Molenda       }
9685fe4d141SJason Molenda     }
9695fe4d141SJason Molenda 
970b9c1b51eSKate Stone     if (addresses.size() > 0) {
97105097246SAdrian Prantl       // First check whether any of the addresses point to Indirect symbols,
97205097246SAdrian Prantl       // and if they do, resolve them:
9735fe4d141SJason Molenda       std::vector<lldb::addr_t> load_addrs;
974b9c1b51eSKate Stone       for (Address address : addresses) {
9755fe4d141SJason Molenda         Symbol *symbol = address.CalculateSymbolContextSymbol();
976b9c1b51eSKate Stone         if (symbol && symbol->IsIndirect()) {
97797206d57SZachary Turner           Status error;
9785fe4d141SJason Molenda           Address symbol_address = symbol->GetAddress();
979b9c1b51eSKate Stone           addr_t resolved_addr = thread.GetProcess()->ResolveIndirectFunction(
980b9c1b51eSKate Stone               &symbol_address, error);
981b9c1b51eSKate Stone           if (error.Success()) {
9825fe4d141SJason Molenda             load_addrs.push_back(resolved_addr);
98363e5fb76SJonas Devlieghere             LLDB_LOGF(log,
98463e5fb76SJonas Devlieghere                       "ResolveIndirectFunction found resolved target for "
985b9c1b51eSKate Stone                       "%s at 0x%" PRIx64 ".",
9865fe4d141SJason Molenda                       symbol->GetName().GetCString(), resolved_addr);
9875fe4d141SJason Molenda           }
988b9c1b51eSKate Stone         } else {
9895fe4d141SJason Molenda           load_addrs.push_back(address.GetLoadAddress(target_sp.get()));
9905fe4d141SJason Molenda         }
9915fe4d141SJason Molenda       }
992796ac80bSJonas Devlieghere       thread_plan_sp = std::make_shared<ThreadPlanRunToAddress>(
993796ac80bSJonas Devlieghere           thread, load_addrs, stop_others);
9945fe4d141SJason Molenda     }
995b9c1b51eSKate Stone   } else {
99663e5fb76SJonas Devlieghere     LLDB_LOGF(log, "Could not find symbol for step through.");
9975fe4d141SJason Molenda   }
9985fe4d141SJason Molenda 
9995fe4d141SJason Molenda   return thread_plan_sp;
10005fe4d141SJason Molenda }
10015fe4d141SJason Molenda 
FindEquivalentSymbols(lldb_private::Symbol * original_symbol,lldb_private::ModuleList & images,lldb_private::SymbolContextList & equivalent_symbols)10021ad655e2SAdrian Prantl void DynamicLoaderDarwin::FindEquivalentSymbols(
1003b9c1b51eSKate Stone     lldb_private::Symbol *original_symbol, lldb_private::ModuleList &images,
1004b9c1b51eSKate Stone     lldb_private::SymbolContextList &equivalent_symbols) {
100522b04487SAlex Langford   ConstString trampoline_name =
100622b04487SAlex Langford       original_symbol->GetMangled().GetName(Mangled::ePreferMangled);
10075fe4d141SJason Molenda   if (!trampoline_name)
10081ad655e2SAdrian Prantl     return;
10095fe4d141SJason Molenda 
10105fe4d141SJason Molenda   static const char *resolver_name_regex = "(_gc|_non_gc|\\$[A-Za-z0-9\\$]+)$";
10115fe4d141SJason Molenda   std::string equivalent_regex_buf("^");
10125fe4d141SJason Molenda   equivalent_regex_buf.append(trampoline_name.GetCString());
10135fe4d141SJason Molenda   equivalent_regex_buf.append(resolver_name_regex);
10145fe4d141SJason Molenda 
101595eae423SZachary Turner   RegularExpression equivalent_name_regex(equivalent_regex_buf);
1016b9c1b51eSKate Stone   images.FindSymbolsMatchingRegExAndType(equivalent_name_regex, eSymbolTypeCode,
10171ad655e2SAdrian Prantl                                          equivalent_symbols);
10185fe4d141SJason Molenda 
10195fe4d141SJason Molenda }
10205fe4d141SJason Molenda 
GetPThreadLibraryModule()1021b9c1b51eSKate Stone lldb::ModuleSP DynamicLoaderDarwin::GetPThreadLibraryModule() {
10225fe4d141SJason Molenda   ModuleSP module_sp = m_libpthread_module_wp.lock();
1023b9c1b51eSKate Stone   if (!module_sp) {
10245fe4d141SJason Molenda     SymbolContextList sc_list;
10255fe4d141SJason Molenda     ModuleSpec module_spec;
1026*1b4b12a3SNico Weber     module_spec.GetFileSpec().GetFilename().SetCString(
1027*1b4b12a3SNico Weber         "libsystem_pthread.dylib");
10285fe4d141SJason Molenda     ModuleList module_list;
10291ad655e2SAdrian Prantl     m_process->GetTarget().GetImages().FindModules(module_spec, module_list);
10301ad655e2SAdrian Prantl     if (!module_list.IsEmpty()) {
1031b9c1b51eSKate Stone       if (module_list.GetSize() == 1) {
10325fe4d141SJason Molenda         module_sp = module_list.GetModuleAtIndex(0);
10335fe4d141SJason Molenda         if (module_sp)
10345fe4d141SJason Molenda           m_libpthread_module_wp = module_sp;
10355fe4d141SJason Molenda       }
10365fe4d141SJason Molenda     }
10375fe4d141SJason Molenda   }
10385fe4d141SJason Molenda   return module_sp;
10395fe4d141SJason Molenda }
10405fe4d141SJason Molenda 
GetPthreadSetSpecificAddress()1041b9c1b51eSKate Stone Address DynamicLoaderDarwin::GetPthreadSetSpecificAddress() {
1042b9c1b51eSKate Stone   if (!m_pthread_getspecific_addr.IsValid()) {
10435fe4d141SJason Molenda     ModuleSP module_sp = GetPThreadLibraryModule();
1044b9c1b51eSKate Stone     if (module_sp) {
10455fe4d141SJason Molenda       lldb_private::SymbolContextList sc_list;
1046b9c1b51eSKate Stone       module_sp->FindSymbolsWithNameAndType(ConstString("pthread_getspecific"),
1047b9c1b51eSKate Stone                                             eSymbolTypeCode, sc_list);
10485fe4d141SJason Molenda       SymbolContext sc;
1049b9c1b51eSKate Stone       if (sc_list.GetContextAtIndex(0, sc)) {
10505fe4d141SJason Molenda         if (sc.symbol)
10515fe4d141SJason Molenda           m_pthread_getspecific_addr = sc.symbol->GetAddress();
10525fe4d141SJason Molenda       }
10535fe4d141SJason Molenda     }
10545fe4d141SJason Molenda   }
10555fe4d141SJason Molenda   return m_pthread_getspecific_addr;
10565fe4d141SJason Molenda }
10575fe4d141SJason Molenda 
10585fe4d141SJason Molenda lldb::addr_t
GetThreadLocalData(const lldb::ModuleSP module_sp,const lldb::ThreadSP thread_sp,lldb::addr_t tls_file_addr)1059b9c1b51eSKate Stone DynamicLoaderDarwin::GetThreadLocalData(const lldb::ModuleSP module_sp,
1060b9c1b51eSKate Stone                                         const lldb::ThreadSP thread_sp,
1061b9c1b51eSKate Stone                                         lldb::addr_t tls_file_addr) {
10625fe4d141SJason Molenda   if (!thread_sp || !module_sp)
10635fe4d141SJason Molenda     return LLDB_INVALID_ADDRESS;
10645fe4d141SJason Molenda 
10655fe4d141SJason Molenda   std::lock_guard<std::recursive_mutex> guard(m_mutex);
10665fe4d141SJason Molenda 
10675fe4d141SJason Molenda   const uint32_t addr_size = m_process->GetAddressByteSize();
10685fe4d141SJason Molenda   uint8_t buf[sizeof(lldb::addr_t) * 3];
10695fe4d141SJason Molenda 
10705fe4d141SJason Molenda   lldb_private::Address tls_addr;
1071b9c1b51eSKate Stone   if (module_sp->ResolveFileAddress(tls_file_addr, tls_addr)) {
107297206d57SZachary Turner     Status error;
10735fe4d141SJason Molenda     const size_t tsl_data_size = addr_size * 3;
10745fe4d141SJason Molenda     Target &target = m_process->GetTarget();
1075e9fe788dSJason Molenda     if (target.ReadMemory(tls_addr, buf, tsl_data_size, error, true) ==
1076b9c1b51eSKate Stone         tsl_data_size) {
10775fe4d141SJason Molenda       const ByteOrder byte_order = m_process->GetByteOrder();
10785fe4d141SJason Molenda       DataExtractor data(buf, sizeof(buf), byte_order, addr_size);
10795fe4d141SJason Molenda       lldb::offset_t offset = addr_size; // Skip the first pointer
10805fe4d141SJason Molenda       const lldb::addr_t pthread_key = data.GetAddress(&offset);
10815fe4d141SJason Molenda       const lldb::addr_t tls_offset = data.GetAddress(&offset);
1082b9c1b51eSKate Stone       if (pthread_key != 0) {
108305097246SAdrian Prantl         // First check to see if we have already figured out the location of
108405097246SAdrian Prantl         // TLS data for the pthread_key on a specific thread yet. If we have we
108505097246SAdrian Prantl         // can re-use it since its location will not change unless the process
108605097246SAdrian Prantl         // execs.
10875fe4d141SJason Molenda         const tid_t tid = thread_sp->GetID();
10885fe4d141SJason Molenda         auto tid_pos = m_tid_to_tls_map.find(tid);
1089b9c1b51eSKate Stone         if (tid_pos != m_tid_to_tls_map.end()) {
10905fe4d141SJason Molenda           auto tls_pos = tid_pos->second.find(pthread_key);
1091b9c1b51eSKate Stone           if (tls_pos != tid_pos->second.end()) {
10925fe4d141SJason Molenda             return tls_pos->second + tls_offset;
10935fe4d141SJason Molenda           }
10945fe4d141SJason Molenda         }
10955fe4d141SJason Molenda         StackFrameSP frame_sp = thread_sp->GetStackFrameAtIndex(0);
1096b9c1b51eSKate Stone         if (frame_sp) {
10976e3b0cc2SRaphael Isemann           TypeSystemClang *clang_ast_context =
1098594308c7SRaphael Isemann               ScratchTypeSystemClang::GetForTarget(target);
10995fe4d141SJason Molenda 
11005fe4d141SJason Molenda           if (!clang_ast_context)
11015fe4d141SJason Molenda             return LLDB_INVALID_ADDRESS;
11025fe4d141SJason Molenda 
1103b9c1b51eSKate Stone           CompilerType clang_void_ptr_type =
1104b9c1b51eSKate Stone               clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
11055fe4d141SJason Molenda           Address pthread_getspecific_addr = GetPthreadSetSpecificAddress();
1106b9c1b51eSKate Stone           if (pthread_getspecific_addr.IsValid()) {
11075fe4d141SJason Molenda             EvaluateExpressionOptions options;
11085fe4d141SJason Molenda 
1109b9c1b51eSKate Stone             lldb::ThreadPlanSP thread_plan_sp(new ThreadPlanCallFunction(
1110b9c1b51eSKate Stone                 *thread_sp, pthread_getspecific_addr, clang_void_ptr_type,
11115fe4d141SJason Molenda                 llvm::ArrayRef<lldb::addr_t>(pthread_key), options));
11125fe4d141SJason Molenda 
11135fe4d141SJason Molenda             DiagnosticManager execution_errors;
11145fe4d141SJason Molenda             ExecutionContext exe_ctx(thread_sp);
1115b9c1b51eSKate Stone             lldb::ExpressionResults results = m_process->RunThreadPlan(
1116b9c1b51eSKate Stone                 exe_ctx, thread_plan_sp, options, execution_errors);
11175fe4d141SJason Molenda 
1118b9c1b51eSKate Stone             if (results == lldb::eExpressionCompleted) {
1119b9c1b51eSKate Stone               lldb::ValueObjectSP result_valobj_sp =
1120b9c1b51eSKate Stone                   thread_plan_sp->GetReturnValueObject();
1121b9c1b51eSKate Stone               if (result_valobj_sp) {
1122b9c1b51eSKate Stone                 const lldb::addr_t pthread_key_data =
1123b9c1b51eSKate Stone                     result_valobj_sp->GetValueAsUnsigned(0);
1124b9c1b51eSKate Stone                 if (pthread_key_data) {
1125b9c1b51eSKate Stone                   m_tid_to_tls_map[tid].insert(
1126b9c1b51eSKate Stone                       std::make_pair(pthread_key, pthread_key_data));
11275fe4d141SJason Molenda                   return pthread_key_data + tls_offset;
11285fe4d141SJason Molenda                 }
11295fe4d141SJason Molenda               }
11305fe4d141SJason Molenda             }
11315fe4d141SJason Molenda           }
11325fe4d141SJason Molenda         }
11335fe4d141SJason Molenda       }
11345fe4d141SJason Molenda     }
11355fe4d141SJason Molenda   }
11365fe4d141SJason Molenda   return LLDB_INVALID_ADDRESS;
11375fe4d141SJason Molenda }
11385fe4d141SJason Molenda 
UseDYLDSPI(Process * process)1139b9c1b51eSKate Stone bool DynamicLoaderDarwin::UseDYLDSPI(Process *process) {
1140a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::DynamicLoader);
11419ab5dc24SJason Molenda   bool use_new_spi_interface = false;
11429ab5dc24SJason Molenda 
11432272c481SPavel Labath   llvm::VersionTuple version = process->GetHostOSVersion();
11442272c481SPavel Labath   if (!version.empty()) {
1145b9c1b51eSKate Stone     const llvm::Triple::OSType os_type =
1146b9c1b51eSKate Stone         process->GetTarget().GetArchitecture().GetTriple().getOS();
11479ab5dc24SJason Molenda 
11489ab5dc24SJason Molenda     // macOS 10.12 and newer
1149b9c1b51eSKate Stone     if (os_type == llvm::Triple::MacOSX &&
11502272c481SPavel Labath         version >= llvm::VersionTuple(10, 12))
11519ab5dc24SJason Molenda       use_new_spi_interface = true;
11529ab5dc24SJason Molenda 
11539ab5dc24SJason Molenda     // iOS 10 and newer
11542272c481SPavel Labath     if (os_type == llvm::Triple::IOS && version >= llvm::VersionTuple(10))
11559ab5dc24SJason Molenda       use_new_spi_interface = true;
11569ab5dc24SJason Molenda 
11579ab5dc24SJason Molenda     // tvOS 10 and newer
11582272c481SPavel Labath     if (os_type == llvm::Triple::TvOS && version >= llvm::VersionTuple(10))
11599ab5dc24SJason Molenda       use_new_spi_interface = true;
11609ab5dc24SJason Molenda 
11619ab5dc24SJason Molenda     // watchOS 3 and newer
11622272c481SPavel Labath     if (os_type == llvm::Triple::WatchOS && version >= llvm::VersionTuple(3))
11639ab5dc24SJason Molenda       use_new_spi_interface = true;
116432762fd2SJason Molenda 
116532762fd2SJason Molenda     // NEED_BRIDGEOS_TRIPLE // Any BridgeOS
116632762fd2SJason Molenda     // NEED_BRIDGEOS_TRIPLE if (os_type == llvm::Triple::BridgeOS)
116732762fd2SJason Molenda     // NEED_BRIDGEOS_TRIPLE   use_new_spi_interface = true;
11689ab5dc24SJason Molenda   }
11699ab5dc24SJason Molenda 
1170b9c1b51eSKate Stone   if (log) {
11719ab5dc24SJason Molenda     if (use_new_spi_interface)
117263e5fb76SJonas Devlieghere       LLDB_LOGF(
117363e5fb76SJonas Devlieghere           log, "DynamicLoaderDarwin::UseDYLDSPI: Use new DynamicLoader plugin");
11749ab5dc24SJason Molenda     else
117563e5fb76SJonas Devlieghere       LLDB_LOGF(
117663e5fb76SJonas Devlieghere           log, "DynamicLoaderDarwin::UseDYLDSPI: Use old DynamicLoader plugin");
11779ab5dc24SJason Molenda   }
11789ab5dc24SJason Molenda   return use_new_spi_interface;
11799ab5dc24SJason Molenda }
1180