blob: f8a7c9d34af8fdc6f760e0a5dbc077da489934a0 [file] [log] [blame]
Jason Molenda5fe4d142016-07-17 21:27:32 +00001//===-- DynamicLoaderDarwin.cpp -----------------------------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Jason Molenda5fe4d142016-07-17 21:27:32 +00006//
7//===----------------------------------------------------------------------===//
8
Pavel Labath1408bf72016-11-01 16:11:14 +00009#include "DynamicLoaderDarwin.h"
10
Jason Molenda5fe4d142016-07-17 21:27:32 +000011#include "lldb/Breakpoint/StoppointCallbackContext.h"
Jason Molenda5fe4d142016-07-17 21:27:32 +000012#include "lldb/Core/Debugger.h"
Jason Molenda5fe4d142016-07-17 21:27:32 +000013#include "lldb/Core/Module.h"
14#include "lldb/Core/ModuleSpec.h"
15#include "lldb/Core/PluginManager.h"
16#include "lldb/Core/Section.h"
Jason Molenda5fe4d142016-07-17 21:27:32 +000017#include "lldb/Expression/DiagnosticManager.h"
Pavel Labath1408bf72016-11-01 16:11:14 +000018#include "lldb/Host/FileSystem.h"
Jason Molenda5fe4d142016-07-17 21:27:32 +000019#include "lldb/Symbol/ClangASTContext.h"
20#include "lldb/Symbol/Function.h"
21#include "lldb/Symbol/ObjectFile.h"
22#include "lldb/Target/ABI.h"
Jason Molenda5fe4d142016-07-17 21:27:32 +000023#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"
Zachary Turner666cc0b2017-03-04 01:30:05 +000029#include "lldb/Utility/DataBuffer.h"
30#include "lldb/Utility/DataBufferHeap.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000031#include "lldb/Utility/Log.h"
Pavel Labathd821c992018-08-07 11:07:21 +000032#include "lldb/Utility/State.h"
Jason Molenda5fe4d142016-07-17 21:27:32 +000033
Alex Langfordb57017102019-07-15 22:56:12 +000034#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
35
Jason Molenda5fe4d142016-07-17 21:27:32 +000036//#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN
37#ifdef ENABLE_DEBUG_PRINTF
38#include <stdio.h>
Kate Stoneb9c1b512016-09-06 20:57:50 +000039#define DEBUG_PRINTF(fmt, ...) printf(fmt, ##__VA_ARGS__)
Jason Molenda5fe4d142016-07-17 21:27:32 +000040#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
Jonas Devlieghere796ac802019-02-11 23:13:08 +000050#include <memory>
51
Jason Molenda5fe4d142016-07-17 21:27:32 +000052using namespace lldb;
53using namespace lldb_private;
54
Jason Molenda5fe4d142016-07-17 21:27:32 +000055// Constructor
Kate Stoneb9c1b512016-09-06 20:57:50 +000056DynamicLoaderDarwin::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() {}
Jason Molenda5fe4d142016-07-17 21:27:32 +000060
Jason Molenda5fe4d142016-07-17 21:27:32 +000061// Destructor
Kate Stoneb9c1b512016-09-06 20:57:50 +000062DynamicLoaderDarwin::~DynamicLoaderDarwin() {}
63
Kate Stoneb9c1b512016-09-06 20:57:50 +000064/// Called after attaching a process.
65///
66/// Allow DynamicLoader plug-ins to execute some code after
67/// attaching to a process.
Kate Stoneb9c1b512016-09-06 20:57:50 +000068void DynamicLoaderDarwin::DidAttach() {
69 PrivateInitialize(m_process);
70 DoInitialImageFetch();
71 SetNotificationBreakpoint();
Jason Molenda5fe4d142016-07-17 21:27:32 +000072}
73
Jason Molenda5fe4d142016-07-17 21:27:32 +000074/// Called after attaching a process.
75///
76/// Allow DynamicLoader plug-ins to execute some code after
77/// attaching to a process.
Kate Stoneb9c1b512016-09-06 20:57:50 +000078void DynamicLoaderDarwin::DidLaunch() {
79 PrivateInitialize(m_process);
80 DoInitialImageFetch();
81 SetNotificationBreakpoint();
Jason Molenda5fe4d142016-07-17 21:27:32 +000082}
83
Jason Molenda5fe4d142016-07-17 21:27:32 +000084// Clear out the state of this class.
Kate Stoneb9c1b512016-09-06 20:57:50 +000085void DynamicLoaderDarwin::Clear(bool clear_process) {
86 std::lock_guard<std::recursive_mutex> guard(m_mutex);
87 if (clear_process)
Konrad Kleine248a1302019-05-23 11:14:47 +000088 m_process = nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +000089 m_dyld_image_infos.clear();
90 m_dyld_image_infos_stop_id = UINT32_MAX;
91 m_dyld.Clear(false);
Jason Molenda5fe4d142016-07-17 21:27:32 +000092}
93
Kate Stoneb9c1b512016-09-06 20:57:50 +000094ModuleSP DynamicLoaderDarwin::FindTargetModuleForImageInfo(
95 ImageInfo &image_info, bool can_create, bool *did_create_ptr) {
96 if (did_create_ptr)
97 *did_create_ptr = false;
Jason Molenda5fe4d142016-07-17 21:27:32 +000098
Kate Stoneb9c1b512016-09-06 20:57:50 +000099 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;
Adrian Prantl24610612019-09-04 17:23:15 +0000103
104 // macCatalyst support: Request matching os/environment.
105 {
106 auto &target_triple = target.GetArchitecture().GetTriple();
107 if (target_triple.getOS() == llvm::Triple::IOS &&
108 target_triple.getEnvironment() == llvm::Triple::MacABI) {
109 // Request the macCatalyst variant of frameworks that have both
110 // a PLATFORM_MACOS and a PLATFORM_MACCATALYST load command.
111 module_spec.GetArchitecture() = ArchSpec(target_triple);
112 }
113 }
114
Kate Stoneb9c1b512016-09-06 20:57:50 +0000115 ModuleSP module_sp(target_images.FindFirstModule(module_spec));
Jason Molenda5fe4d142016-07-17 21:27:32 +0000116
Kate Stoneb9c1b512016-09-06 20:57:50 +0000117 if (module_sp && !module_spec.GetUUID().IsValid() &&
118 !module_sp->GetUUID().IsValid()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000119 // No UUID, we must rely upon the cached module modification time and the
120 // modification time of the file on disk
Kate Stoneb9c1b512016-09-06 20:57:50 +0000121 if (module_sp->GetModificationTime() !=
Jonas Devlieghere46376962018-10-31 21:49:27 +0000122 FileSystem::Instance().GetModificationTime(module_sp->GetFileSpec()))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000123 module_sp.reset();
124 }
125
126 if (!module_sp) {
127 if (can_create) {
Jason Molenda1724a172019-04-08 23:03:02 +0000128 // We'll call Target::ModulesDidLoad after all the modules have been
129 // added to the target, don't let it be called for every one.
130 module_sp = target.GetOrCreateModule(module_spec, false /* notify */);
Konrad Kleine248a1302019-05-23 11:14:47 +0000131 if (!module_sp || module_sp->GetObjectFile() == nullptr)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000132 module_sp = m_process->ReadModuleFromMemory(image_info.file_spec,
133 image_info.address);
134
135 if (did_create_ptr)
136 *did_create_ptr = (bool)module_sp;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000137 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000138 }
139 return module_sp;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000140}
141
Kate Stoneb9c1b512016-09-06 20:57:50 +0000142void DynamicLoaderDarwin::UnloadImages(
143 const std::vector<lldb::addr_t> &solib_addresses) {
144 std::lock_guard<std::recursive_mutex> guard(m_mutex);
145 if (m_process->GetStopID() == m_dyld_image_infos_stop_id)
146 return;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000147
Kate Stoneb9c1b512016-09-06 20:57:50 +0000148 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
149 Target &target = m_process->GetTarget();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000150 LLDB_LOGF(log, "Removing %" PRId64 " modules.",
151 (uint64_t)solib_addresses.size());
Jason Molenda5fe4d142016-07-17 21:27:32 +0000152
Kate Stoneb9c1b512016-09-06 20:57:50 +0000153 ModuleList unloaded_module_list;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000154
Kate Stoneb9c1b512016-09-06 20:57:50 +0000155 for (addr_t solib_addr : solib_addresses) {
156 Address header;
157 if (header.SetLoadAddress(solib_addr, &target)) {
158 if (header.GetOffset() == 0) {
159 ModuleSP module_to_remove(header.GetModule());
160 if (module_to_remove.get()) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000161 LLDB_LOGF(log, "Removing module at address 0x%" PRIx64, solib_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000162 // remove the sections from the Target
163 UnloadSections(module_to_remove);
164 // add this to the list of modules to remove
165 unloaded_module_list.AppendIfNeeded(module_to_remove);
166 // remove the entry from the m_dyld_image_infos
167 ImageInfo::collection::iterator pos, end = m_dyld_image_infos.end();
168 for (pos = m_dyld_image_infos.begin(); pos != end; pos++) {
169 if (solib_addr == (*pos).address) {
170 m_dyld_image_infos.erase(pos);
171 break;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000172 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000173 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000174 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000175 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000176 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000177 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000178
Kate Stoneb9c1b512016-09-06 20:57:50 +0000179 if (unloaded_module_list.GetSize() > 0) {
180 if (log) {
181 log->PutCString("Unloaded:");
182 unloaded_module_list.LogUUIDAndPaths(
183 log, "DynamicLoaderDarwin::UnloadModules");
Jason Molenda5fe4d142016-07-17 21:27:32 +0000184 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000185 m_process->GetTarget().GetImages().Remove(unloaded_module_list);
186 m_dyld_image_infos_stop_id = m_process->GetStopID();
187 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000188}
189
Kate Stoneb9c1b512016-09-06 20:57:50 +0000190void DynamicLoaderDarwin::UnloadAllImages() {
191 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
192 ModuleList unloaded_modules_list;
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000193
Kate Stoneb9c1b512016-09-06 20:57:50 +0000194 Target &target = m_process->GetTarget();
195 const ModuleList &target_modules = target.GetImages();
196 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000197
Kate Stoneb9c1b512016-09-06 20:57:50 +0000198 size_t num_modules = target_modules.GetSize();
199 ModuleSP dyld_sp(GetDYLDModule());
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000200
Kate Stoneb9c1b512016-09-06 20:57:50 +0000201 for (size_t i = 0; i < num_modules; i++) {
202 ModuleSP module_sp = target_modules.GetModuleAtIndexUnlocked(i);
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000203
Kate Stoneb9c1b512016-09-06 20:57:50 +0000204 // Don't remove dyld - else we'll lose our breakpoint notifying us about
Adrian Prantl05097242018-04-30 16:49:04 +0000205 // libraries being re-loaded...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000206 if (module_sp.get() != nullptr && module_sp.get() != dyld_sp.get()) {
207 UnloadSections(module_sp);
208 unloaded_modules_list.Append(module_sp);
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000209 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000210 }
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000211
Kate Stoneb9c1b512016-09-06 20:57:50 +0000212 if (unloaded_modules_list.GetSize() != 0) {
213 if (log) {
214 log->PutCString("Unloaded:");
215 unloaded_modules_list.LogUUIDAndPaths(
216 log, "DynamicLoaderDarwin::UnloadAllImages");
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000217 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000218 target.GetImages().Remove(unloaded_modules_list);
219 m_dyld_image_infos.clear();
220 m_dyld_image_infos_stop_id = m_process->GetStopID();
221 }
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000222}
223
Adrian Prantl05097242018-04-30 16:49:04 +0000224// Update the load addresses for all segments in MODULE using the updated INFO
225// that is passed in.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000226bool DynamicLoaderDarwin::UpdateImageLoadAddress(Module *module,
227 ImageInfo &info) {
228 bool changed = false;
229 if (module) {
230 ObjectFile *image_object_file = module->GetObjectFile();
231 if (image_object_file) {
232 SectionList *section_list = image_object_file->GetSectionList();
233 if (section_list) {
234 std::vector<uint32_t> inaccessible_segment_indexes;
Adrian Prantl05097242018-04-30 16:49:04 +0000235 // We now know the slide amount, so go through all sections and update
236 // the load addresses with the correct values.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000237 const size_t num_segments = info.segments.size();
238 for (size_t i = 0; i < num_segments; ++i) {
Adrian Prantl05097242018-04-30 16:49:04 +0000239 // Only load a segment if it has protections. Things like __PAGEZERO
240 // don't have any protections, and they shouldn't be slid
Kate Stoneb9c1b512016-09-06 20:57:50 +0000241 SectionSP section_sp(
242 section_list->FindSectionByName(info.segments[i].name));
Jason Molenda5fe4d142016-07-17 21:27:32 +0000243
Kate Stoneb9c1b512016-09-06 20:57:50 +0000244 if (info.segments[i].maxprot == 0) {
245 inaccessible_segment_indexes.push_back(i);
246 } else {
247 const addr_t new_section_load_addr =
248 info.segments[i].vmaddr + info.slide;
249 static ConstString g_section_name_LINKEDIT("__LINKEDIT");
Jason Molenda5fe4d142016-07-17 21:27:32 +0000250
Kate Stoneb9c1b512016-09-06 20:57:50 +0000251 if (section_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +0000252 // __LINKEDIT sections from files in the shared cache can overlap
253 // so check to see what the segment name is and pass "false" so
254 // we don't warn of overlapping "Section" objects, and "true" for
255 // all other sections.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000256 const bool warn_multiple =
257 section_sp->GetName() != g_section_name_LINKEDIT;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000258
Kate Stoneb9c1b512016-09-06 20:57:50 +0000259 changed = m_process->GetTarget().SetSectionLoadAddress(
260 section_sp, new_section_load_addr, warn_multiple);
Jason Molenda9073eb42019-01-25 03:01:48 +0000261 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000262 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000263 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000264
Adrian Prantl05097242018-04-30 16:49:04 +0000265 // If the loaded the file (it changed) and we have segments that are
266 // not readable or writeable, add them to the invalid memory region
267 // cache for the process. This will typically only be the __PAGEZERO
268 // segment in the main executable. We might be able to apply this more
269 // generally to more sections that have no protections in the future,
270 // but for now we are going to just do __PAGEZERO.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000271 if (changed && !inaccessible_segment_indexes.empty()) {
272 for (uint32_t i = 0; i < inaccessible_segment_indexes.size(); ++i) {
273 const uint32_t seg_idx = inaccessible_segment_indexes[i];
274 SectionSP section_sp(
275 section_list->FindSectionByName(info.segments[seg_idx].name));
276
277 if (section_sp) {
278 static ConstString g_pagezero_section_name("__PAGEZERO");
279 if (g_pagezero_section_name == section_sp->GetName()) {
280 // __PAGEZERO never slides...
281 const lldb::addr_t vmaddr = info.segments[seg_idx].vmaddr;
282 const lldb::addr_t vmsize = info.segments[seg_idx].vmsize;
283 Process::LoadRange pagezero_range(vmaddr, vmsize);
284 m_process->AddInvalidMemoryRegion(pagezero_range);
285 }
286 }
287 }
288 }
289 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000290 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000291 }
292 // We might have an in memory image that was loaded as soon as it was created
293 if (info.load_stop_id == m_process->GetStopID())
294 changed = true;
295 else if (changed) {
296 // Update the stop ID when this library was updated
297 info.load_stop_id = m_process->GetStopID();
298 }
299 return changed;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000300}
301
Jason Molenda5fe4d142016-07-17 21:27:32 +0000302// Unload the segments in MODULE using the INFO that is passed in.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000303bool DynamicLoaderDarwin::UnloadModuleSections(Module *module,
304 ImageInfo &info) {
305 bool changed = false;
306 if (module) {
307 ObjectFile *image_object_file = module->GetObjectFile();
308 if (image_object_file) {
309 SectionList *section_list = image_object_file->GetSectionList();
310 if (section_list) {
311 const size_t num_segments = info.segments.size();
312 for (size_t i = 0; i < num_segments; ++i) {
313 SectionSP section_sp(
314 section_list->FindSectionByName(info.segments[i].name));
315 if (section_sp) {
316 const addr_t old_section_load_addr =
317 info.segments[i].vmaddr + info.slide;
318 if (m_process->GetTarget().SetSectionUnloaded(
319 section_sp, old_section_load_addr))
320 changed = true;
321 } else {
322 Host::SystemLog(Host::eSystemLogWarning,
323 "warning: unable to find and unload segment named "
324 "'%s' in '%s' in macosx dynamic loader plug-in.\n",
325 info.segments[i].name.AsCString("<invalid>"),
326 image_object_file->GetFileSpec().GetPath().c_str());
327 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000328 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000329 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000330 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000331 }
332 return changed;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000333}
334
Kate Stoneb9c1b512016-09-06 20:57:50 +0000335// Given a JSON dictionary (from debugserver, most likely) of binary images
Adrian Prantl05097242018-04-30 16:49:04 +0000336// loaded in the inferior process, add the images to the ImageInfo collection.
Jason Molenda5fe4d142016-07-17 21:27:32 +0000337
Kate Stoneb9c1b512016-09-06 20:57:50 +0000338bool DynamicLoaderDarwin::JSONImageInformationIntoImageInfo(
339 StructuredData::ObjectSP image_details,
340 ImageInfo::collection &image_infos) {
341 StructuredData::ObjectSP images_sp =
342 image_details->GetAsDictionary()->GetValueForKey("images");
343 if (images_sp.get() == nullptr)
344 return false;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000345
Kate Stoneb9c1b512016-09-06 20:57:50 +0000346 image_infos.resize(images_sp->GetAsArray()->GetSize());
Jason Molenda5fe4d142016-07-17 21:27:32 +0000347
Kate Stoneb9c1b512016-09-06 20:57:50 +0000348 for (size_t i = 0; i < image_infos.size(); i++) {
349 StructuredData::ObjectSP image_sp =
350 images_sp->GetAsArray()->GetItemAtIndex(i);
351 if (image_sp.get() == nullptr || image_sp->GetAsDictionary() == nullptr)
352 return false;
353 StructuredData::Dictionary *image = image_sp->GetAsDictionary();
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000354 // clang-format off
355 if (!image->HasKey("load_address") ||
356 !image->HasKey("pathname") ||
357 !image->HasKey("mod_date") ||
358 !image->HasKey("mach_header") ||
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359 image->GetValueForKey("mach_header")->GetAsDictionary() == nullptr ||
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000360 !image->HasKey("segments") ||
Kate Stoneb9c1b512016-09-06 20:57:50 +0000361 image->GetValueForKey("segments")->GetAsArray() == nullptr ||
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000362 !image->HasKey("uuid")) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000363 return false;
364 }
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000365 // clang-format on
Kate Stoneb9c1b512016-09-06 20:57:50 +0000366 image_infos[i].address =
367 image->GetValueForKey("load_address")->GetAsInteger()->GetValue();
368 image_infos[i].mod_date =
369 image->GetValueForKey("mod_date")->GetAsInteger()->GetValue();
370 image_infos[i].file_spec.SetFile(
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000371 image->GetValueForKey("pathname")->GetAsString()->GetValue(),
Jonas Devlieghere937348c2018-06-13 22:08:14 +0000372 FileSpec::Style::native);
Jason Molenda5fe4d142016-07-17 21:27:32 +0000373
Kate Stoneb9c1b512016-09-06 20:57:50 +0000374 StructuredData::Dictionary *mh =
375 image->GetValueForKey("mach_header")->GetAsDictionary();
376 image_infos[i].header.magic =
377 mh->GetValueForKey("magic")->GetAsInteger()->GetValue();
378 image_infos[i].header.cputype =
379 mh->GetValueForKey("cputype")->GetAsInteger()->GetValue();
380 image_infos[i].header.cpusubtype =
381 mh->GetValueForKey("cpusubtype")->GetAsInteger()->GetValue();
382 image_infos[i].header.filetype =
383 mh->GetValueForKey("filetype")->GetAsInteger()->GetValue();
Jason Molenda5fe4d142016-07-17 21:27:32 +0000384
Kate Stoneb9c1b512016-09-06 20:57:50 +0000385 if (image->HasKey("min_version_os_name")) {
386 std::string os_name = image->GetValueForKey("min_version_os_name")
387 ->GetAsString()
388 ->GetValue();
389 if (os_name == "macosx")
390 image_infos[i].os_type = llvm::Triple::MacOSX;
391 else if (os_name == "ios" || os_name == "iphoneos")
392 image_infos[i].os_type = llvm::Triple::IOS;
393 else if (os_name == "tvos")
394 image_infos[i].os_type = llvm::Triple::TvOS;
395 else if (os_name == "watchos")
396 image_infos[i].os_type = llvm::Triple::WatchOS;
Jason Molenda32762fd2018-10-11 00:28:35 +0000397 // NEED_BRIDGEOS_TRIPLE else if (os_name == "bridgeos")
398 // NEED_BRIDGEOS_TRIPLE image_infos[i].os_type = llvm::Triple::BridgeOS;
Adrian Prantl24610612019-09-04 17:23:15 +0000399 else if (os_name == "maccatalyst") {
400 image_infos[i].os_type = llvm::Triple::IOS;
401 image_infos[i].os_env = llvm::Triple::MacABI;
402 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000403 }
404 if (image->HasKey("min_version_os_sdk")) {
405 image_infos[i].min_version_os_sdk =
406 image->GetValueForKey("min_version_os_sdk")
407 ->GetAsString()
408 ->GetValue();
Jason Molenda5fe4d142016-07-17 21:27:32 +0000409 }
410
Kate Stoneb9c1b512016-09-06 20:57:50 +0000411 // Fields that aren't used by DynamicLoaderDarwin so debugserver doesn't
Adrian Prantl05097242018-04-30 16:49:04 +0000412 // currently send them in the reply.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000413
414 if (mh->HasKey("flags"))
415 image_infos[i].header.flags =
416 mh->GetValueForKey("flags")->GetAsInteger()->GetValue();
417 else
418 image_infos[i].header.flags = 0;
419
420 if (mh->HasKey("ncmds"))
421 image_infos[i].header.ncmds =
422 mh->GetValueForKey("ncmds")->GetAsInteger()->GetValue();
423 else
424 image_infos[i].header.ncmds = 0;
425
426 if (mh->HasKey("sizeofcmds"))
427 image_infos[i].header.sizeofcmds =
428 mh->GetValueForKey("sizeofcmds")->GetAsInteger()->GetValue();
429 else
430 image_infos[i].header.sizeofcmds = 0;
431
432 StructuredData::Array *segments =
433 image->GetValueForKey("segments")->GetAsArray();
434 uint32_t segcount = segments->GetSize();
435 for (size_t j = 0; j < segcount; j++) {
436 Segment segment;
437 StructuredData::Dictionary *seg =
438 segments->GetItemAtIndex(j)->GetAsDictionary();
Zachary Turner28333212017-05-12 05:49:54 +0000439 segment.name =
440 ConstString(seg->GetValueForKey("name")->GetAsString()->GetValue());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000441 segment.vmaddr =
442 seg->GetValueForKey("vmaddr")->GetAsInteger()->GetValue();
443 segment.vmsize =
444 seg->GetValueForKey("vmsize")->GetAsInteger()->GetValue();
445 segment.fileoff =
446 seg->GetValueForKey("fileoff")->GetAsInteger()->GetValue();
447 segment.filesize =
448 seg->GetValueForKey("filesize")->GetAsInteger()->GetValue();
449 segment.maxprot =
450 seg->GetValueForKey("maxprot")->GetAsInteger()->GetValue();
451
452 // Fields that aren't used by DynamicLoaderDarwin so debugserver doesn't
Adrian Prantl05097242018-04-30 16:49:04 +0000453 // currently send them in the reply.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000454
455 if (seg->HasKey("initprot"))
456 segment.initprot =
457 seg->GetValueForKey("initprot")->GetAsInteger()->GetValue();
458 else
459 segment.initprot = 0;
460
461 if (seg->HasKey("flags"))
462 segment.flags =
463 seg->GetValueForKey("flags")->GetAsInteger()->GetValue();
464 else
465 segment.flags = 0;
466
467 if (seg->HasKey("nsects"))
468 segment.nsects =
469 seg->GetValueForKey("nsects")->GetAsInteger()->GetValue();
470 else
471 segment.nsects = 0;
472
473 image_infos[i].segments.push_back(segment);
474 }
475
Jim Inghamf3ecbfc2019-01-24 22:43:44 +0000476 image_infos[i].uuid.SetFromOptionalStringRef(
Zachary Turner28333212017-05-12 05:49:54 +0000477 image->GetValueForKey("uuid")->GetAsString()->GetValue());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000478
Adrian Prantl05097242018-04-30 16:49:04 +0000479 // All sections listed in the dyld image info structure will all either be
480 // fixed up already, or they will all be off by a single slide amount that
481 // is determined by finding the first segment that is at file offset zero
482 // which also has bytes (a file size that is greater than zero) in the
483 // object file.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000484
485 // Determine the slide amount (if any)
486 const size_t num_sections = image_infos[i].segments.size();
487 for (size_t k = 0; k < num_sections; ++k) {
Adrian Prantl05097242018-04-30 16:49:04 +0000488 // Iterate through the object file sections to find the first section
489 // that starts of file offset zero and that has bytes in the file...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000490 if ((image_infos[i].segments[k].fileoff == 0 &&
491 image_infos[i].segments[k].filesize > 0) ||
Raphael Isemann05cfdb02019-04-26 07:21:36 +0000492 (image_infos[i].segments[k].name == "__TEXT")) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000493 image_infos[i].slide =
494 image_infos[i].address - image_infos[i].segments[k].vmaddr;
Adrian Prantl05097242018-04-30 16:49:04 +0000495 // We have found the slide amount, so we can exit this for loop.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000496 break;
497 }
498 }
499 }
500
501 return true;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000502}
503
Kate Stoneb9c1b512016-09-06 20:57:50 +0000504void DynamicLoaderDarwin::UpdateSpecialBinariesFromNewImageInfos(
505 ImageInfo::collection &image_infos) {
506 uint32_t exe_idx = UINT32_MAX;
507 uint32_t dyld_idx = UINT32_MAX;
508 Target &target = m_process->GetTarget();
509 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
510 ConstString g_dyld_sim_filename("dyld_sim");
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000511
Kate Stoneb9c1b512016-09-06 20:57:50 +0000512 ArchSpec target_arch = target.GetArchitecture();
513 const size_t image_infos_size = image_infos.size();
514 for (size_t i = 0; i < image_infos_size; i++) {
515 if (image_infos[i].header.filetype == llvm::MachO::MH_DYLINKER) {
Jason Molenda32762fd2018-10-11 00:28:35 +0000516 // In a "simulator" process (an x86 process that is
517 // ios/tvos/watchos/bridgeos) we will have two dyld modules --
518 // a "dyld" that we want to keep track of, and a "dyld_sim" which
519 // we don't need to keep track of here. If the target is an x86
520 // system and the OS of the dyld binary is ios/tvos/watchos/bridgeos,
521 // then we are looking at dyld_sym.
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000522
Adrian Prantl05097242018-04-30 16:49:04 +0000523 // debugserver has only recently (late 2016) started sending up the os
524 // type for each binary it sees -- so if we don't have an os type, use a
525 // filename check as our next best guess.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000526 if (image_infos[i].os_type == llvm::Triple::OSType::UnknownOS) {
527 if (image_infos[i].file_spec.GetFilename() != g_dyld_sim_filename) {
528 dyld_idx = i;
529 }
530 } else if (target_arch.GetTriple().getArch() == llvm::Triple::x86 ||
531 target_arch.GetTriple().getArch() == llvm::Triple::x86_64) {
532 if (image_infos[i].os_type != llvm::Triple::OSType::IOS &&
533 image_infos[i].os_type != llvm::Triple::TvOS &&
534 image_infos[i].os_type != llvm::Triple::WatchOS) {
Jason Molenda32762fd2018-10-11 00:28:35 +0000535 // NEED_BRIDGEOS_TRIPLE image_infos[i].os_type != llvm::Triple::BridgeOS) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000536 dyld_idx = i;
537 }
538 }
Jason Molenda777fcec2017-01-21 01:17:36 +0000539 else {
Adrian Prantl05097242018-04-30 16:49:04 +0000540 // catch-all for any other environment -- trust that dyld is actually
541 // dyld
Jason Molenda777fcec2017-01-21 01:17:36 +0000542 dyld_idx = i;
543 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000544 } else if (image_infos[i].header.filetype == llvm::MachO::MH_EXECUTE) {
545 exe_idx = i;
546 }
547 }
548
549 if (exe_idx != UINT32_MAX) {
550 const bool can_create = true;
Konrad Kleine248a1302019-05-23 11:14:47 +0000551 ModuleSP exe_module_sp(FindTargetModuleForImageInfo(image_infos[exe_idx],
552 can_create, nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000553 if (exe_module_sp) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000554 LLDB_LOGF(log, "Found executable module: %s",
555 exe_module_sp->GetFileSpec().GetPath().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000556 target.GetImages().AppendIfNeeded(exe_module_sp);
557 UpdateImageLoadAddress(exe_module_sp.get(), image_infos[exe_idx]);
558 if (exe_module_sp.get() != target.GetExecutableModulePointer()) {
Jonas Devliegheref9a07e92018-09-20 09:09:05 +0000559 target.SetExecutableModule(exe_module_sp, eLoadDependentsNo);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000560 }
561 }
562 }
563
564 if (dyld_idx != UINT32_MAX) {
565 const bool can_create = true;
Konrad Kleine248a1302019-05-23 11:14:47 +0000566 ModuleSP dyld_sp = FindTargetModuleForImageInfo(image_infos[dyld_idx],
567 can_create, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000568 if (dyld_sp.get()) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000569 LLDB_LOGF(log, "Found dyld module: %s",
570 dyld_sp->GetFileSpec().GetPath().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000571 target.GetImages().AppendIfNeeded(dyld_sp);
572 UpdateImageLoadAddress(dyld_sp.get(), image_infos[dyld_idx]);
573 SetDYLDModule(dyld_sp);
574 }
575 }
576}
577
578void DynamicLoaderDarwin::UpdateDYLDImageInfoFromNewImageInfo(
579 ImageInfo &image_info) {
580 if (image_info.header.filetype == llvm::MachO::MH_DYLINKER) {
581 const bool can_create = true;
582 ModuleSP dyld_sp =
Konrad Kleine248a1302019-05-23 11:14:47 +0000583 FindTargetModuleForImageInfo(image_info, can_create, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000584 if (dyld_sp.get()) {
585 Target &target = m_process->GetTarget();
586 target.GetImages().AppendIfNeeded(dyld_sp);
587 UpdateImageLoadAddress(dyld_sp.get(), image_info);
588 SetDYLDModule(dyld_sp);
589 }
590 }
591}
592
593void DynamicLoaderDarwin::SetDYLDModule(lldb::ModuleSP &dyld_module_sp) {
594 m_dyld_module_wp = dyld_module_sp;
595}
596
597ModuleSP DynamicLoaderDarwin::GetDYLDModule() {
598 ModuleSP dyld_sp(m_dyld_module_wp.lock());
599 return dyld_sp;
600}
601
602bool DynamicLoaderDarwin::AddModulesUsingImageInfos(
603 ImageInfo::collection &image_infos) {
604 std::lock_guard<std::recursive_mutex> guard(m_mutex);
605 // Now add these images to the main list.
606 ModuleList loaded_module_list;
607 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
608 Target &target = m_process->GetTarget();
609 ModuleList &target_images = target.GetImages();
610
611 for (uint32_t idx = 0; idx < image_infos.size(); ++idx) {
612 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000613 LLDB_LOGF(log, "Adding new image at address=0x%16.16" PRIx64 ".",
614 image_infos[idx].address);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000615 image_infos[idx].PutToLog(log);
616 }
617
618 m_dyld_image_infos.push_back(image_infos[idx]);
619
620 ModuleSP image_module_sp(
Konrad Kleine248a1302019-05-23 11:14:47 +0000621 FindTargetModuleForImageInfo(image_infos[idx], true, nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000622
623 if (image_module_sp) {
624 ObjectFile *objfile = image_module_sp->GetObjectFile();
625 if (objfile) {
626 SectionList *sections = objfile->GetSectionList();
627 if (sections) {
628 ConstString commpage_dbstr("__commpage");
629 Section *commpage_section =
630 sections->FindSectionByName(commpage_dbstr).get();
631 if (commpage_section) {
632 ModuleSpec module_spec(objfile->GetFileSpec(),
633 image_infos[idx].GetArchitecture());
634 module_spec.GetObjectName() = commpage_dbstr;
635 ModuleSP commpage_image_module_sp(
636 target_images.FindFirstModule(module_spec));
637 if (!commpage_image_module_sp) {
638 module_spec.SetObjectOffset(objfile->GetFileOffset() +
639 commpage_section->GetFileOffset());
640 module_spec.SetObjectSize(objfile->GetByteSize());
Jason Molenda1724a172019-04-08 23:03:02 +0000641 commpage_image_module_sp = target.GetOrCreateModule(module_spec,
642 true /* notify */);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000643 if (!commpage_image_module_sp ||
Konrad Kleine248a1302019-05-23 11:14:47 +0000644 commpage_image_module_sp->GetObjectFile() == nullptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000645 commpage_image_module_sp = m_process->ReadModuleFromMemory(
646 image_infos[idx].file_spec, image_infos[idx].address);
647 // Always load a memory image right away in the target in case
648 // we end up trying to read the symbol table from memory... The
649 // __LINKEDIT will need to be mapped so we can figure out where
650 // the symbol table bits are...
651 bool changed = false;
652 UpdateImageLoadAddress(commpage_image_module_sp.get(),
653 image_infos[idx]);
654 target.GetImages().Append(commpage_image_module_sp);
655 if (changed) {
656 image_infos[idx].load_stop_id = m_process->GetStopID();
657 loaded_module_list.AppendIfNeeded(commpage_image_module_sp);
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000658 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000659 }
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000660 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000661 }
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000662 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000663 }
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000664
Adrian Prantl05097242018-04-30 16:49:04 +0000665 // UpdateImageLoadAddress will return true if any segments change load
666 // address. We need to check this so we don't mention that all loaded
667 // shared libraries are newly loaded each time we hit out dyld breakpoint
668 // since dyld will list all shared libraries each time.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000669 if (UpdateImageLoadAddress(image_module_sp.get(), image_infos[idx])) {
670 target_images.AppendIfNeeded(image_module_sp);
671 loaded_module_list.AppendIfNeeded(image_module_sp);
672 }
Adrian Prantl24610612019-09-04 17:23:15 +0000673
674 // macCataylst support:
675 // Update the module's platform with the DYLD info.
676 ArchSpec dyld_spec = image_infos[idx].GetArchitecture();
677 if (dyld_spec.GetTriple().getOS() == llvm::Triple::IOS &&
678 dyld_spec.GetTriple().getEnvironment() == llvm::Triple::MacABI) {
679 image_module_sp->MergeArchitecture(dyld_spec);
680 const auto &target_triple = target.GetArchitecture().GetTriple();
681 // If dyld reports the process as being loaded as MACCATALYST,
682 // force-update the target's architecture to MACCATALYST.
683 if (!(target_triple.getOS() == llvm::Triple::IOS &&
684 target_triple.getEnvironment() == llvm::Triple::MacABI))
685 target.SetArchitecture(dyld_spec);
686 }
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000687 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000688 }
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000689
Kate Stoneb9c1b512016-09-06 20:57:50 +0000690 if (loaded_module_list.GetSize() > 0) {
691 if (log)
692 loaded_module_list.LogUUIDAndPaths(log,
693 "DynamicLoaderDarwin::ModulesDidLoad");
694 m_process->GetTarget().ModulesDidLoad(loaded_module_list);
695 }
696 return true;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000697}
698
Jason Molenda5fe4d142016-07-17 21:27:32 +0000699// On Mac OS X libobjc (the Objective-C runtime) has several critical dispatch
Adrian Prantl05097242018-04-30 16:49:04 +0000700// functions written in hand-written assembly, and also have hand-written
701// unwind information in the eh_frame section. Normally we prefer analyzing
702// the assembly instructions of a currently executing frame to unwind from that
703// frame -- but on hand-written functions this profiling can fail. We should
704// use the eh_frame instructions for these functions all the time.
Jason Molenda5fe4d142016-07-17 21:27:32 +0000705//
706// As an aside, it would be better if the eh_frame entries had a flag (or were
707// extensible so they could have an Apple-specific flag) which indicates that
708// the instructions are asynchronous -- accurate at every instruction, instead
709// of our normal default assumption that they are not.
Jason Molenda5fe4d142016-07-17 21:27:32 +0000710
Kate Stoneb9c1b512016-09-06 20:57:50 +0000711bool DynamicLoaderDarwin::AlwaysRelyOnEHUnwindInfo(SymbolContext &sym_ctx) {
712 ModuleSP module_sp;
713 if (sym_ctx.symbol) {
714 module_sp = sym_ctx.symbol->GetAddressRef().GetModule();
715 }
Konrad Kleine248a1302019-05-23 11:14:47 +0000716 if (module_sp.get() == nullptr && sym_ctx.function) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000717 module_sp =
718 sym_ctx.function->GetAddressRange().GetBaseAddress().GetModule();
719 }
Konrad Kleine248a1302019-05-23 11:14:47 +0000720 if (module_sp.get() == nullptr)
Jason Molenda5fe4d142016-07-17 21:27:32 +0000721 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000722
Alex Langforde823bbe2019-06-10 20:53:23 +0000723 ObjCLanguageRuntime *objc_runtime = ObjCLanguageRuntime::Get(*m_process);
Konrad Kleine248a1302019-05-23 11:14:47 +0000724 return objc_runtime != nullptr &&
725 objc_runtime->IsModuleObjCLibrary(module_sp);
Jason Molenda5fe4d142016-07-17 21:27:32 +0000726}
727
Jason Molenda5fe4d142016-07-17 21:27:32 +0000728// Dump a Segment to the file handle provided.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000729void DynamicLoaderDarwin::Segment::PutToLog(Log *log,
730 lldb::addr_t slide) const {
731 if (log) {
732 if (slide == 0)
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000733 LLDB_LOGF(log, "\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ")",
734 name.AsCString(""), vmaddr + slide, vmaddr + slide + vmsize);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000735 else
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000736 LLDB_LOGF(log,
737 "\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64
738 ") slide = 0x%" PRIx64,
739 name.AsCString(""), vmaddr + slide, vmaddr + slide + vmsize,
740 slide);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000741 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000742}
743
Adrian Prantl24610612019-09-04 17:23:15 +0000744lldb_private::ArchSpec DynamicLoaderDarwin::ImageInfo::GetArchitecture() const {
745 // Update the module's platform with the DYLD info.
746 lldb_private::ArchSpec arch_spec(lldb_private::eArchTypeMachO, header.cputype,
747 header.cpusubtype);
748 if (os_type == llvm::Triple::IOS && os_env == llvm::Triple::MacABI) {
749 llvm::Triple triple(llvm::Twine("x86_64-apple-ios") + min_version_os_sdk +
750 "-macabi");
751 ArchSpec maccatalyst_spec(triple);
752 if (arch_spec.IsCompatibleMatch(maccatalyst_spec))
753 arch_spec.MergeFrom(maccatalyst_spec);
754 }
755 return arch_spec;
756}
757
Jason Molenda5fe4d142016-07-17 21:27:32 +0000758const DynamicLoaderDarwin::Segment *
Adrian Prantl0e4c4822019-03-06 21:22:25 +0000759DynamicLoaderDarwin::ImageInfo::FindSegment(ConstString name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000760 const size_t num_segments = segments.size();
761 for (size_t i = 0; i < num_segments; ++i) {
762 if (segments[i].name == name)
763 return &segments[i];
764 }
Konrad Kleine248a1302019-05-23 11:14:47 +0000765 return nullptr;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000766}
767
Jason Molenda5fe4d142016-07-17 21:27:32 +0000768// Dump an image info structure to the file handle provided.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000769void DynamicLoaderDarwin::ImageInfo::PutToLog(Log *log) const {
Pavel Labathfbb14282018-06-20 20:13:04 +0000770 if (!log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000771 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000772 if (address == LLDB_INVALID_ADDRESS) {
Pavel Labathfbb14282018-06-20 20:13:04 +0000773 LLDB_LOG(log, "modtime={0:x+8} uuid={1} path='{2}' (UNLOADED)", mod_date,
774 uuid.GetAsString(), file_spec.GetPath());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000775 } else {
Pavel Labathfbb14282018-06-20 20:13:04 +0000776 LLDB_LOG(log, "address={0:x+16} modtime={1:x+8} uuid={2} path='{3}'",
777 address, mod_date, uuid.GetAsString(), file_spec.GetPath());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000778 for (uint32_t i = 0; i < segments.size(); ++i)
779 segments[i].PutToLog(log, slide);
780 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000781}
782
Kate Stoneb9c1b512016-09-06 20:57:50 +0000783void DynamicLoaderDarwin::PrivateInitialize(Process *process) {
784 DEBUG_PRINTF("DynamicLoaderDarwin::%s() process state = %s\n", __FUNCTION__,
785 StateAsCString(m_process->GetState()));
786 Clear(true);
787 m_process = process;
788 m_process->GetTarget().ClearAllLoadedSections();
Jason Molenda5fe4d142016-07-17 21:27:32 +0000789}
790
Jason Molenda5fe4d142016-07-17 21:27:32 +0000791// Member function that gets called when the process state changes.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000792void DynamicLoaderDarwin::PrivateProcessStateChanged(Process *process,
793 StateType state) {
794 DEBUG_PRINTF("DynamicLoaderDarwin::%s(%s)\n", __FUNCTION__,
795 StateAsCString(state));
796 switch (state) {
797 case eStateConnected:
798 case eStateAttaching:
799 case eStateLaunching:
800 case eStateInvalid:
801 case eStateUnloaded:
802 case eStateExited:
803 case eStateDetached:
804 Clear(false);
805 break;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000806
Kate Stoneb9c1b512016-09-06 20:57:50 +0000807 case eStateStopped:
Adrian Prantl05097242018-04-30 16:49:04 +0000808 // Keep trying find dyld and set our notification breakpoint each time we
809 // stop until we succeed
Kate Stoneb9c1b512016-09-06 20:57:50 +0000810 if (!DidSetNotificationBreakpoint() && m_process->IsAlive()) {
811 if (NeedToDoInitialImageFetch())
812 DoInitialImageFetch();
Jason Molenda5fe4d142016-07-17 21:27:32 +0000813
Kate Stoneb9c1b512016-09-06 20:57:50 +0000814 SetNotificationBreakpoint();
Jason Molenda5fe4d142016-07-17 21:27:32 +0000815 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000816 break;
817
818 case eStateRunning:
819 case eStateStepping:
820 case eStateCrashed:
821 case eStateSuspended:
822 break;
823 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000824}
825
826ThreadPlanSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000827DynamicLoaderDarwin::GetStepThroughTrampolinePlan(Thread &thread,
828 bool stop_others) {
829 ThreadPlanSP thread_plan_sp;
830 StackFrame *current_frame = thread.GetStackFrameAtIndex(0).get();
831 const SymbolContext &current_context =
832 current_frame->GetSymbolContext(eSymbolContextSymbol);
833 Symbol *current_symbol = current_context.symbol;
834 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
835 TargetSP target_sp(thread.CalculateTarget());
Jason Molenda5fe4d142016-07-17 21:27:32 +0000836
Konrad Kleine248a1302019-05-23 11:14:47 +0000837 if (current_symbol != nullptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000838 std::vector<Address> addresses;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000839
Kate Stoneb9c1b512016-09-06 20:57:50 +0000840 if (current_symbol->IsTrampoline()) {
Adrian Prantl0e4c4822019-03-06 21:22:25 +0000841 ConstString trampoline_name = current_symbol->GetMangled().GetName(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000842 current_symbol->GetLanguage(), Mangled::ePreferMangled);
Jason Molenda5fe4d142016-07-17 21:27:32 +0000843
Kate Stoneb9c1b512016-09-06 20:57:50 +0000844 if (trampoline_name) {
845 const ModuleList &images = target_sp->GetImages();
846
847 SymbolContextList code_symbols;
848 images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeCode,
849 code_symbols);
850 size_t num_code_symbols = code_symbols.GetSize();
851
852 if (num_code_symbols > 0) {
853 for (uint32_t i = 0; i < num_code_symbols; i++) {
854 SymbolContext context;
855 AddressRange addr_range;
856 if (code_symbols.GetContextAtIndex(i, context)) {
857 context.GetAddressRange(eSymbolContextEverything, 0, false,
858 addr_range);
859 addresses.push_back(addr_range.GetBaseAddress());
860 if (log) {
861 addr_t load_addr =
862 addr_range.GetBaseAddress().GetLoadAddress(target_sp.get());
863
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000864 LLDB_LOGF(log,
865 "Found a trampoline target symbol at 0x%" PRIx64 ".",
866 load_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000867 }
868 }
869 }
870 }
871
872 SymbolContextList reexported_symbols;
873 images.FindSymbolsWithNameAndType(
874 trampoline_name, eSymbolTypeReExported, reexported_symbols);
875 size_t num_reexported_symbols = reexported_symbols.GetSize();
876 if (num_reexported_symbols > 0) {
877 for (uint32_t i = 0; i < num_reexported_symbols; i++) {
878 SymbolContext context;
879 if (reexported_symbols.GetContextAtIndex(i, context)) {
880 if (context.symbol) {
881 Symbol *actual_symbol =
882 context.symbol->ResolveReExportedSymbol(*target_sp.get());
883 if (actual_symbol) {
884 const Address actual_symbol_addr =
885 actual_symbol->GetAddress();
886 if (actual_symbol_addr.IsValid()) {
887 addresses.push_back(actual_symbol_addr);
888 if (log) {
889 lldb::addr_t load_addr =
890 actual_symbol_addr.GetLoadAddress(target_sp.get());
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000891 LLDB_LOGF(
892 log,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000893 "Found a re-exported symbol: %s at 0x%" PRIx64 ".",
894 actual_symbol->GetName().GetCString(), load_addr);
Jason Molenda5fe4d142016-07-17 21:27:32 +0000895 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000896 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000897 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000898 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000899 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000900 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000901 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000902
903 SymbolContextList indirect_symbols;
904 images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeResolver,
905 indirect_symbols);
906 size_t num_indirect_symbols = indirect_symbols.GetSize();
907 if (num_indirect_symbols > 0) {
908 for (uint32_t i = 0; i < num_indirect_symbols; i++) {
909 SymbolContext context;
910 AddressRange addr_range;
911 if (indirect_symbols.GetContextAtIndex(i, context)) {
912 context.GetAddressRange(eSymbolContextEverything, 0, false,
913 addr_range);
914 addresses.push_back(addr_range.GetBaseAddress());
915 if (log) {
916 addr_t load_addr =
917 addr_range.GetBaseAddress().GetLoadAddress(target_sp.get());
918
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000919 LLDB_LOGF(log,
920 "Found an indirect target symbol at 0x%" PRIx64 ".",
921 load_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000922 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000923 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000924 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000925 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000926 }
927 } else if (current_symbol->GetType() == eSymbolTypeReExported) {
928 // I am not sure we could ever end up stopped AT a re-exported symbol.
929 // But just in case:
930
931 const Symbol *actual_symbol =
932 current_symbol->ResolveReExportedSymbol(*(target_sp.get()));
933 if (actual_symbol) {
934 Address target_addr(actual_symbol->GetAddress());
935 if (target_addr.IsValid()) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000936 LLDB_LOGF(
937 log,
938 "Found a re-exported symbol: %s pointing to: %s at 0x%" PRIx64
939 ".",
940 current_symbol->GetName().GetCString(),
941 actual_symbol->GetName().GetCString(),
942 target_addr.GetLoadAddress(target_sp.get()));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000943 addresses.push_back(target_addr.GetLoadAddress(target_sp.get()));
Jason Molenda5fe4d142016-07-17 21:27:32 +0000944 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000945 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000946 }
947
Kate Stoneb9c1b512016-09-06 20:57:50 +0000948 if (addresses.size() > 0) {
Adrian Prantl05097242018-04-30 16:49:04 +0000949 // First check whether any of the addresses point to Indirect symbols,
950 // and if they do, resolve them:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000951 std::vector<lldb::addr_t> load_addrs;
952 for (Address address : addresses) {
953 Symbol *symbol = address.CalculateSymbolContextSymbol();
954 if (symbol && symbol->IsIndirect()) {
Zachary Turner97206d52017-05-12 04:51:55 +0000955 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000956 Address symbol_address = symbol->GetAddress();
957 addr_t resolved_addr = thread.GetProcess()->ResolveIndirectFunction(
958 &symbol_address, error);
959 if (error.Success()) {
960 load_addrs.push_back(resolved_addr);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000961 LLDB_LOGF(log,
962 "ResolveIndirectFunction found resolved target for "
963 "%s at 0x%" PRIx64 ".",
964 symbol->GetName().GetCString(), resolved_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000965 }
966 } else {
967 load_addrs.push_back(address.GetLoadAddress(target_sp.get()));
Jason Molenda5fe4d142016-07-17 21:27:32 +0000968 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000969 }
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000970 thread_plan_sp = std::make_shared<ThreadPlanRunToAddress>(
971 thread, load_addrs, stop_others);
Jason Molenda5fe4d142016-07-17 21:27:32 +0000972 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000973 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000974 LLDB_LOGF(log, "Could not find symbol for step through.");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000975 }
976
977 return thread_plan_sp;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000978}
979
Adrian Prantl1ad655e2019-10-17 19:56:40 +0000980void DynamicLoaderDarwin::FindEquivalentSymbols(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000981 lldb_private::Symbol *original_symbol, lldb_private::ModuleList &images,
982 lldb_private::SymbolContextList &equivalent_symbols) {
Adrian Prantl0e4c4822019-03-06 21:22:25 +0000983 ConstString trampoline_name = original_symbol->GetMangled().GetName(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000984 original_symbol->GetLanguage(), Mangled::ePreferMangled);
985 if (!trampoline_name)
Adrian Prantl1ad655e2019-10-17 19:56:40 +0000986 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000987
988 static const char *resolver_name_regex = "(_gc|_non_gc|\\$[A-Za-z0-9\\$]+)$";
989 std::string equivalent_regex_buf("^");
990 equivalent_regex_buf.append(trampoline_name.GetCString());
991 equivalent_regex_buf.append(resolver_name_regex);
992
Zachary Turner95eae422016-09-21 16:01:28 +0000993 RegularExpression equivalent_name_regex(equivalent_regex_buf);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000994 images.FindSymbolsMatchingRegExAndType(equivalent_name_regex, eSymbolTypeCode,
Adrian Prantl1ad655e2019-10-17 19:56:40 +0000995 equivalent_symbols);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000996
Kate Stoneb9c1b512016-09-06 20:57:50 +0000997}
998
999lldb::ModuleSP DynamicLoaderDarwin::GetPThreadLibraryModule() {
1000 ModuleSP module_sp = m_libpthread_module_wp.lock();
1001 if (!module_sp) {
1002 SymbolContextList sc_list;
1003 ModuleSpec module_spec;
1004 module_spec.GetFileSpec().GetFilename().SetCString(
1005 "libsystem_pthread.dylib");
1006 ModuleList module_list;
Adrian Prantl1ad655e2019-10-17 19:56:40 +00001007 m_process->GetTarget().GetImages().FindModules(module_spec, module_list);
1008 if (!module_list.IsEmpty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001009 if (module_list.GetSize() == 1) {
1010 module_sp = module_list.GetModuleAtIndex(0);
Jason Molenda5fe4d142016-07-17 21:27:32 +00001011 if (module_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001012 m_libpthread_module_wp = module_sp;
1013 }
Jason Molenda5fe4d142016-07-17 21:27:32 +00001014 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001015 }
1016 return module_sp;
1017}
1018
1019Address DynamicLoaderDarwin::GetPthreadSetSpecificAddress() {
1020 if (!m_pthread_getspecific_addr.IsValid()) {
1021 ModuleSP module_sp = GetPThreadLibraryModule();
1022 if (module_sp) {
1023 lldb_private::SymbolContextList sc_list;
1024 module_sp->FindSymbolsWithNameAndType(ConstString("pthread_getspecific"),
1025 eSymbolTypeCode, sc_list);
1026 SymbolContext sc;
1027 if (sc_list.GetContextAtIndex(0, sc)) {
1028 if (sc.symbol)
1029 m_pthread_getspecific_addr = sc.symbol->GetAddress();
1030 }
1031 }
1032 }
1033 return m_pthread_getspecific_addr;
Jason Molenda5fe4d142016-07-17 21:27:32 +00001034}
1035
1036lldb::addr_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001037DynamicLoaderDarwin::GetThreadLocalData(const lldb::ModuleSP module_sp,
1038 const lldb::ThreadSP thread_sp,
1039 lldb::addr_t tls_file_addr) {
1040 if (!thread_sp || !module_sp)
Jason Molenda5fe4d142016-07-17 21:27:32 +00001041 return LLDB_INVALID_ADDRESS;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001042
1043 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1044
1045 const uint32_t addr_size = m_process->GetAddressByteSize();
1046 uint8_t buf[sizeof(lldb::addr_t) * 3];
1047
1048 lldb_private::Address tls_addr;
1049 if (module_sp->ResolveFileAddress(tls_file_addr, tls_addr)) {
Zachary Turner97206d52017-05-12 04:51:55 +00001050 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001051 const size_t tsl_data_size = addr_size * 3;
1052 Target &target = m_process->GetTarget();
1053 if (target.ReadMemory(tls_addr, false, buf, tsl_data_size, error) ==
1054 tsl_data_size) {
1055 const ByteOrder byte_order = m_process->GetByteOrder();
1056 DataExtractor data(buf, sizeof(buf), byte_order, addr_size);
1057 lldb::offset_t offset = addr_size; // Skip the first pointer
1058 const lldb::addr_t pthread_key = data.GetAddress(&offset);
1059 const lldb::addr_t tls_offset = data.GetAddress(&offset);
1060 if (pthread_key != 0) {
Adrian Prantl05097242018-04-30 16:49:04 +00001061 // First check to see if we have already figured out the location of
1062 // TLS data for the pthread_key on a specific thread yet. If we have we
1063 // can re-use it since its location will not change unless the process
1064 // execs.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001065 const tid_t tid = thread_sp->GetID();
1066 auto tid_pos = m_tid_to_tls_map.find(tid);
1067 if (tid_pos != m_tid_to_tls_map.end()) {
1068 auto tls_pos = tid_pos->second.find(pthread_key);
1069 if (tls_pos != tid_pos->second.end()) {
1070 return tls_pos->second + tls_offset;
1071 }
1072 }
1073 StackFrameSP frame_sp = thread_sp->GetStackFrameAtIndex(0);
1074 if (frame_sp) {
1075 ClangASTContext *clang_ast_context =
1076 target.GetScratchClangASTContext();
1077
1078 if (!clang_ast_context)
1079 return LLDB_INVALID_ADDRESS;
1080
1081 CompilerType clang_void_ptr_type =
1082 clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
1083 Address pthread_getspecific_addr = GetPthreadSetSpecificAddress();
1084 if (pthread_getspecific_addr.IsValid()) {
1085 EvaluateExpressionOptions options;
1086
1087 lldb::ThreadPlanSP thread_plan_sp(new ThreadPlanCallFunction(
1088 *thread_sp, pthread_getspecific_addr, clang_void_ptr_type,
1089 llvm::ArrayRef<lldb::addr_t>(pthread_key), options));
1090
1091 DiagnosticManager execution_errors;
1092 ExecutionContext exe_ctx(thread_sp);
1093 lldb::ExpressionResults results = m_process->RunThreadPlan(
1094 exe_ctx, thread_plan_sp, options, execution_errors);
1095
1096 if (results == lldb::eExpressionCompleted) {
1097 lldb::ValueObjectSP result_valobj_sp =
1098 thread_plan_sp->GetReturnValueObject();
1099 if (result_valobj_sp) {
1100 const lldb::addr_t pthread_key_data =
1101 result_valobj_sp->GetValueAsUnsigned(0);
1102 if (pthread_key_data) {
1103 m_tid_to_tls_map[tid].insert(
1104 std::make_pair(pthread_key, pthread_key_data));
1105 return pthread_key_data + tls_offset;
1106 }
1107 }
1108 }
1109 }
1110 }
1111 }
1112 }
1113 }
1114 return LLDB_INVALID_ADDRESS;
Jason Molenda5fe4d142016-07-17 21:27:32 +00001115}
1116
Kate Stoneb9c1b512016-09-06 20:57:50 +00001117bool DynamicLoaderDarwin::UseDYLDSPI(Process *process) {
1118 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001119 bool use_new_spi_interface = false;
Jason Molenda9ab5dc22016-07-21 08:30:55 +00001120
Pavel Labath2272c482018-06-18 15:02:23 +00001121 llvm::VersionTuple version = process->GetHostOSVersion();
1122 if (!version.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001123 const llvm::Triple::OSType os_type =
1124 process->GetTarget().GetArchitecture().GetTriple().getOS();
Jason Molenda9ab5dc22016-07-21 08:30:55 +00001125
Kate Stoneb9c1b512016-09-06 20:57:50 +00001126 // macOS 10.12 and newer
1127 if (os_type == llvm::Triple::MacOSX &&
Pavel Labath2272c482018-06-18 15:02:23 +00001128 version >= llvm::VersionTuple(10, 12))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001129 use_new_spi_interface = true;
Jason Molenda9ab5dc22016-07-21 08:30:55 +00001130
Kate Stoneb9c1b512016-09-06 20:57:50 +00001131 // iOS 10 and newer
Pavel Labath2272c482018-06-18 15:02:23 +00001132 if (os_type == llvm::Triple::IOS && version >= llvm::VersionTuple(10))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001133 use_new_spi_interface = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001134
1135 // tvOS 10 and newer
Pavel Labath2272c482018-06-18 15:02:23 +00001136 if (os_type == llvm::Triple::TvOS && version >= llvm::VersionTuple(10))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001137 use_new_spi_interface = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001138
1139 // watchOS 3 and newer
Pavel Labath2272c482018-06-18 15:02:23 +00001140 if (os_type == llvm::Triple::WatchOS && version >= llvm::VersionTuple(3))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001141 use_new_spi_interface = true;
Jason Molenda32762fd2018-10-11 00:28:35 +00001142
1143 // NEED_BRIDGEOS_TRIPLE // Any BridgeOS
1144 // NEED_BRIDGEOS_TRIPLE if (os_type == llvm::Triple::BridgeOS)
1145 // NEED_BRIDGEOS_TRIPLE use_new_spi_interface = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001146 }
1147
Kate Stoneb9c1b512016-09-06 20:57:50 +00001148 if (log) {
1149 if (use_new_spi_interface)
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001150 LLDB_LOGF(
1151 log, "DynamicLoaderDarwin::UseDYLDSPI: Use new DynamicLoader plugin");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001152 else
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001153 LLDB_LOGF(
1154 log, "DynamicLoaderDarwin::UseDYLDSPI: Use old DynamicLoader plugin");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001155 }
1156 return use_new_spi_interface;
Jason Molenda9ab5dc22016-07-21 08:30:55 +00001157}