blob: 6f7e93d170f04940c9c0353956ba6adf878c6d8b [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"
23#include "lldb/Target/ObjCLanguageRuntime.h"
24#include "lldb/Target/RegisterContext.h"
25#include "lldb/Target/StackFrame.h"
26#include "lldb/Target/Target.h"
27#include "lldb/Target/Thread.h"
28#include "lldb/Target/ThreadPlanCallFunction.h"
29#include "lldb/Target/ThreadPlanRunToAddress.h"
Zachary Turner666cc0b2017-03-04 01:30:05 +000030#include "lldb/Utility/DataBuffer.h"
31#include "lldb/Utility/DataBufferHeap.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000032#include "lldb/Utility/Log.h"
Pavel Labathd821c992018-08-07 11:07:21 +000033#include "lldb/Utility/State.h"
Jason Molenda5fe4d142016-07-17 21:27:32 +000034
Jason Molenda5fe4d142016-07-17 21:27:32 +000035//#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN
36#ifdef ENABLE_DEBUG_PRINTF
37#include <stdio.h>
Kate Stoneb9c1b512016-09-06 20:57:50 +000038#define DEBUG_PRINTF(fmt, ...) printf(fmt, ##__VA_ARGS__)
Jason Molenda5fe4d142016-07-17 21:27:32 +000039#else
40#define DEBUG_PRINTF(fmt, ...)
41#endif
42
43#ifndef __APPLE__
44#include "Utility/UuidCompatibility.h"
45#else
46#include <uuid/uuid.h>
47#endif
48
49using namespace lldb;
50using namespace lldb_private;
51
Jason Molenda5fe4d142016-07-17 21:27:32 +000052//----------------------------------------------------------------------
53// Constructor
54//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +000055DynamicLoaderDarwin::DynamicLoaderDarwin(Process *process)
56 : DynamicLoader(process), m_dyld_module_wp(), m_libpthread_module_wp(),
57 m_pthread_getspecific_addr(), m_tid_to_tls_map(), m_dyld_image_infos(),
58 m_dyld_image_infos_stop_id(UINT32_MAX), m_dyld(), m_mutex() {}
Jason Molenda5fe4d142016-07-17 21:27:32 +000059
60//----------------------------------------------------------------------
61// Destructor
62//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +000063DynamicLoaderDarwin::~DynamicLoaderDarwin() {}
64
65//------------------------------------------------------------------
66/// Called after attaching a process.
67///
68/// Allow DynamicLoader plug-ins to execute some code after
69/// attaching to a process.
70//------------------------------------------------------------------
71void DynamicLoaderDarwin::DidAttach() {
72 PrivateInitialize(m_process);
73 DoInitialImageFetch();
74 SetNotificationBreakpoint();
Jason Molenda5fe4d142016-07-17 21:27:32 +000075}
76
77//------------------------------------------------------------------
78/// Called after attaching a process.
79///
80/// Allow DynamicLoader plug-ins to execute some code after
81/// attaching to a process.
82//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +000083void DynamicLoaderDarwin::DidLaunch() {
84 PrivateInitialize(m_process);
85 DoInitialImageFetch();
86 SetNotificationBreakpoint();
Jason Molenda5fe4d142016-07-17 21:27:32 +000087}
88
Jason Molenda5fe4d142016-07-17 21:27:32 +000089//----------------------------------------------------------------------
90// Clear out the state of this class.
91//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +000092void DynamicLoaderDarwin::Clear(bool clear_process) {
93 std::lock_guard<std::recursive_mutex> guard(m_mutex);
94 if (clear_process)
95 m_process = NULL;
96 m_dyld_image_infos.clear();
97 m_dyld_image_infos_stop_id = UINT32_MAX;
98 m_dyld.Clear(false);
Jason Molenda5fe4d142016-07-17 21:27:32 +000099}
100
Kate Stoneb9c1b512016-09-06 20:57:50 +0000101ModuleSP DynamicLoaderDarwin::FindTargetModuleForImageInfo(
102 ImageInfo &image_info, bool can_create, bool *did_create_ptr) {
103 if (did_create_ptr)
104 *did_create_ptr = false;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000105
Kate Stoneb9c1b512016-09-06 20:57:50 +0000106 Target &target = m_process->GetTarget();
107 const ModuleList &target_images = target.GetImages();
108 ModuleSpec module_spec(image_info.file_spec);
109 module_spec.GetUUID() = image_info.uuid;
110 ModuleSP module_sp(target_images.FindFirstModule(module_spec));
Jason Molenda5fe4d142016-07-17 21:27:32 +0000111
Kate Stoneb9c1b512016-09-06 20:57:50 +0000112 if (module_sp && !module_spec.GetUUID().IsValid() &&
113 !module_sp->GetUUID().IsValid()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000114 // No UUID, we must rely upon the cached module modification time and the
115 // modification time of the file on disk
Kate Stoneb9c1b512016-09-06 20:57:50 +0000116 if (module_sp->GetModificationTime() !=
Jonas Devlieghere46376962018-10-31 21:49:27 +0000117 FileSystem::Instance().GetModificationTime(module_sp->GetFileSpec()))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000118 module_sp.reset();
119 }
120
121 if (!module_sp) {
122 if (can_create) {
123 module_sp = target.GetSharedModule(module_spec);
124 if (!module_sp || module_sp->GetObjectFile() == NULL)
125 module_sp = m_process->ReadModuleFromMemory(image_info.file_spec,
126 image_info.address);
127
128 if (did_create_ptr)
129 *did_create_ptr = (bool)module_sp;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000130 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000131 }
132 return module_sp;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000133}
134
Kate Stoneb9c1b512016-09-06 20:57:50 +0000135void DynamicLoaderDarwin::UnloadImages(
136 const std::vector<lldb::addr_t> &solib_addresses) {
137 std::lock_guard<std::recursive_mutex> guard(m_mutex);
138 if (m_process->GetStopID() == m_dyld_image_infos_stop_id)
139 return;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000140
Kate Stoneb9c1b512016-09-06 20:57:50 +0000141 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
142 Target &target = m_process->GetTarget();
143 if (log)
144 log->Printf("Removing %" PRId64 " modules.",
145 (uint64_t)solib_addresses.size());
Jason Molenda5fe4d142016-07-17 21:27:32 +0000146
Kate Stoneb9c1b512016-09-06 20:57:50 +0000147 ModuleList unloaded_module_list;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000148
Kate Stoneb9c1b512016-09-06 20:57:50 +0000149 for (addr_t solib_addr : solib_addresses) {
150 Address header;
151 if (header.SetLoadAddress(solib_addr, &target)) {
152 if (header.GetOffset() == 0) {
153 ModuleSP module_to_remove(header.GetModule());
154 if (module_to_remove.get()) {
155 if (log)
156 log->Printf("Removing module at address 0x%" PRIx64, solib_addr);
157 // remove the sections from the Target
158 UnloadSections(module_to_remove);
159 // add this to the list of modules to remove
160 unloaded_module_list.AppendIfNeeded(module_to_remove);
161 // remove the entry from the m_dyld_image_infos
162 ImageInfo::collection::iterator pos, end = m_dyld_image_infos.end();
163 for (pos = m_dyld_image_infos.begin(); pos != end; pos++) {
164 if (solib_addr == (*pos).address) {
165 m_dyld_image_infos.erase(pos);
166 break;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000167 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000168 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000169 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000170 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000171 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000172 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000173
Kate Stoneb9c1b512016-09-06 20:57:50 +0000174 if (unloaded_module_list.GetSize() > 0) {
175 if (log) {
176 log->PutCString("Unloaded:");
177 unloaded_module_list.LogUUIDAndPaths(
178 log, "DynamicLoaderDarwin::UnloadModules");
Jason Molenda5fe4d142016-07-17 21:27:32 +0000179 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000180 m_process->GetTarget().GetImages().Remove(unloaded_module_list);
181 m_dyld_image_infos_stop_id = m_process->GetStopID();
182 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000183}
184
Kate Stoneb9c1b512016-09-06 20:57:50 +0000185void DynamicLoaderDarwin::UnloadAllImages() {
186 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
187 ModuleList unloaded_modules_list;
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000188
Kate Stoneb9c1b512016-09-06 20:57:50 +0000189 Target &target = m_process->GetTarget();
190 const ModuleList &target_modules = target.GetImages();
191 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000192
Kate Stoneb9c1b512016-09-06 20:57:50 +0000193 size_t num_modules = target_modules.GetSize();
194 ModuleSP dyld_sp(GetDYLDModule());
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000195
Kate Stoneb9c1b512016-09-06 20:57:50 +0000196 for (size_t i = 0; i < num_modules; i++) {
197 ModuleSP module_sp = target_modules.GetModuleAtIndexUnlocked(i);
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000198
Kate Stoneb9c1b512016-09-06 20:57:50 +0000199 // Don't remove dyld - else we'll lose our breakpoint notifying us about
Adrian Prantl05097242018-04-30 16:49:04 +0000200 // libraries being re-loaded...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000201 if (module_sp.get() != nullptr && module_sp.get() != dyld_sp.get()) {
202 UnloadSections(module_sp);
203 unloaded_modules_list.Append(module_sp);
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000204 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000205 }
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000206
Kate Stoneb9c1b512016-09-06 20:57:50 +0000207 if (unloaded_modules_list.GetSize() != 0) {
208 if (log) {
209 log->PutCString("Unloaded:");
210 unloaded_modules_list.LogUUIDAndPaths(
211 log, "DynamicLoaderDarwin::UnloadAllImages");
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000212 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000213 target.GetImages().Remove(unloaded_modules_list);
214 m_dyld_image_infos.clear();
215 m_dyld_image_infos_stop_id = m_process->GetStopID();
216 }
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000217}
218
Jason Molenda5fe4d142016-07-17 21:27:32 +0000219//----------------------------------------------------------------------
Adrian Prantl05097242018-04-30 16:49:04 +0000220// Update the load addresses for all segments in MODULE using the updated INFO
221// that is passed in.
Jason Molenda5fe4d142016-07-17 21:27:32 +0000222//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000223bool DynamicLoaderDarwin::UpdateImageLoadAddress(Module *module,
224 ImageInfo &info) {
225 bool changed = false;
226 if (module) {
227 ObjectFile *image_object_file = module->GetObjectFile();
228 if (image_object_file) {
229 SectionList *section_list = image_object_file->GetSectionList();
230 if (section_list) {
231 std::vector<uint32_t> inaccessible_segment_indexes;
Adrian Prantl05097242018-04-30 16:49:04 +0000232 // We now know the slide amount, so go through all sections and update
233 // the load addresses with the correct values.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000234 const size_t num_segments = info.segments.size();
235 for (size_t i = 0; i < num_segments; ++i) {
Adrian Prantl05097242018-04-30 16:49:04 +0000236 // Only load a segment if it has protections. Things like __PAGEZERO
237 // don't have any protections, and they shouldn't be slid
Kate Stoneb9c1b512016-09-06 20:57:50 +0000238 SectionSP section_sp(
239 section_list->FindSectionByName(info.segments[i].name));
Jason Molenda5fe4d142016-07-17 21:27:32 +0000240
Kate Stoneb9c1b512016-09-06 20:57:50 +0000241 if (info.segments[i].maxprot == 0) {
242 inaccessible_segment_indexes.push_back(i);
243 } else {
244 const addr_t new_section_load_addr =
245 info.segments[i].vmaddr + info.slide;
246 static ConstString g_section_name_LINKEDIT("__LINKEDIT");
Jason Molenda5fe4d142016-07-17 21:27:32 +0000247
Kate Stoneb9c1b512016-09-06 20:57:50 +0000248 if (section_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +0000249 // __LINKEDIT sections from files in the shared cache can overlap
250 // so check to see what the segment name is and pass "false" so
251 // we don't warn of overlapping "Section" objects, and "true" for
252 // all other sections.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000253 const bool warn_multiple =
254 section_sp->GetName() != g_section_name_LINKEDIT;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000255
Kate Stoneb9c1b512016-09-06 20:57:50 +0000256 changed = m_process->GetTarget().SetSectionLoadAddress(
257 section_sp, new_section_load_addr, warn_multiple);
Jason Molenda9073eb42019-01-25 03:01:48 +0000258 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000259 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000260 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000261
Adrian Prantl05097242018-04-30 16:49:04 +0000262 // If the loaded the file (it changed) and we have segments that are
263 // not readable or writeable, add them to the invalid memory region
264 // cache for the process. This will typically only be the __PAGEZERO
265 // segment in the main executable. We might be able to apply this more
266 // generally to more sections that have no protections in the future,
267 // but for now we are going to just do __PAGEZERO.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000268 if (changed && !inaccessible_segment_indexes.empty()) {
269 for (uint32_t i = 0; i < inaccessible_segment_indexes.size(); ++i) {
270 const uint32_t seg_idx = inaccessible_segment_indexes[i];
271 SectionSP section_sp(
272 section_list->FindSectionByName(info.segments[seg_idx].name));
273
274 if (section_sp) {
275 static ConstString g_pagezero_section_name("__PAGEZERO");
276 if (g_pagezero_section_name == section_sp->GetName()) {
277 // __PAGEZERO never slides...
278 const lldb::addr_t vmaddr = info.segments[seg_idx].vmaddr;
279 const lldb::addr_t vmsize = info.segments[seg_idx].vmsize;
280 Process::LoadRange pagezero_range(vmaddr, vmsize);
281 m_process->AddInvalidMemoryRegion(pagezero_range);
282 }
283 }
284 }
285 }
286 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000287 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000288 }
289 // We might have an in memory image that was loaded as soon as it was created
290 if (info.load_stop_id == m_process->GetStopID())
291 changed = true;
292 else if (changed) {
293 // Update the stop ID when this library was updated
294 info.load_stop_id = m_process->GetStopID();
295 }
296 return changed;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000297}
298
299//----------------------------------------------------------------------
300// Unload the segments in MODULE using the INFO that is passed in.
301//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000302bool DynamicLoaderDarwin::UnloadModuleSections(Module *module,
303 ImageInfo &info) {
304 bool changed = false;
305 if (module) {
306 ObjectFile *image_object_file = module->GetObjectFile();
307 if (image_object_file) {
308 SectionList *section_list = image_object_file->GetSectionList();
309 if (section_list) {
310 const size_t num_segments = info.segments.size();
311 for (size_t i = 0; i < num_segments; ++i) {
312 SectionSP section_sp(
313 section_list->FindSectionByName(info.segments[i].name));
314 if (section_sp) {
315 const addr_t old_section_load_addr =
316 info.segments[i].vmaddr + info.slide;
317 if (m_process->GetTarget().SetSectionUnloaded(
318 section_sp, old_section_load_addr))
319 changed = true;
320 } else {
321 Host::SystemLog(Host::eSystemLogWarning,
322 "warning: unable to find and unload segment named "
323 "'%s' in '%s' in macosx dynamic loader plug-in.\n",
324 info.segments[i].name.AsCString("<invalid>"),
325 image_object_file->GetFileSpec().GetPath().c_str());
326 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000327 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000328 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000329 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000330 }
331 return changed;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000332}
333
Kate Stoneb9c1b512016-09-06 20:57:50 +0000334// Given a JSON dictionary (from debugserver, most likely) of binary images
Adrian Prantl05097242018-04-30 16:49:04 +0000335// loaded in the inferior process, add the images to the ImageInfo collection.
Jason Molenda5fe4d142016-07-17 21:27:32 +0000336
Kate Stoneb9c1b512016-09-06 20:57:50 +0000337bool DynamicLoaderDarwin::JSONImageInformationIntoImageInfo(
338 StructuredData::ObjectSP image_details,
339 ImageInfo::collection &image_infos) {
340 StructuredData::ObjectSP images_sp =
341 image_details->GetAsDictionary()->GetValueForKey("images");
342 if (images_sp.get() == nullptr)
343 return false;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000344
Kate Stoneb9c1b512016-09-06 20:57:50 +0000345 image_infos.resize(images_sp->GetAsArray()->GetSize());
Jason Molenda5fe4d142016-07-17 21:27:32 +0000346
Kate Stoneb9c1b512016-09-06 20:57:50 +0000347 for (size_t i = 0; i < image_infos.size(); i++) {
348 StructuredData::ObjectSP image_sp =
349 images_sp->GetAsArray()->GetItemAtIndex(i);
350 if (image_sp.get() == nullptr || image_sp->GetAsDictionary() == nullptr)
351 return false;
352 StructuredData::Dictionary *image = image_sp->GetAsDictionary();
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000353 // clang-format off
354 if (!image->HasKey("load_address") ||
355 !image->HasKey("pathname") ||
356 !image->HasKey("mod_date") ||
357 !image->HasKey("mach_header") ||
Kate Stoneb9c1b512016-09-06 20:57:50 +0000358 image->GetValueForKey("mach_header")->GetAsDictionary() == nullptr ||
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000359 !image->HasKey("segments") ||
Kate Stoneb9c1b512016-09-06 20:57:50 +0000360 image->GetValueForKey("segments")->GetAsArray() == nullptr ||
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000361 !image->HasKey("uuid")) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000362 return false;
363 }
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000364 // clang-format on
Kate Stoneb9c1b512016-09-06 20:57:50 +0000365 image_infos[i].address =
366 image->GetValueForKey("load_address")->GetAsInteger()->GetValue();
367 image_infos[i].mod_date =
368 image->GetValueForKey("mod_date")->GetAsInteger()->GetValue();
369 image_infos[i].file_spec.SetFile(
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000370 image->GetValueForKey("pathname")->GetAsString()->GetValue(),
Jonas Devlieghere937348c2018-06-13 22:08:14 +0000371 FileSpec::Style::native);
Jason Molenda5fe4d142016-07-17 21:27:32 +0000372
Kate Stoneb9c1b512016-09-06 20:57:50 +0000373 StructuredData::Dictionary *mh =
374 image->GetValueForKey("mach_header")->GetAsDictionary();
375 image_infos[i].header.magic =
376 mh->GetValueForKey("magic")->GetAsInteger()->GetValue();
377 image_infos[i].header.cputype =
378 mh->GetValueForKey("cputype")->GetAsInteger()->GetValue();
379 image_infos[i].header.cpusubtype =
380 mh->GetValueForKey("cpusubtype")->GetAsInteger()->GetValue();
381 image_infos[i].header.filetype =
382 mh->GetValueForKey("filetype")->GetAsInteger()->GetValue();
Jason Molenda5fe4d142016-07-17 21:27:32 +0000383
Kate Stoneb9c1b512016-09-06 20:57:50 +0000384 if (image->HasKey("min_version_os_name")) {
385 std::string os_name = image->GetValueForKey("min_version_os_name")
386 ->GetAsString()
387 ->GetValue();
388 if (os_name == "macosx")
389 image_infos[i].os_type = llvm::Triple::MacOSX;
390 else if (os_name == "ios" || os_name == "iphoneos")
391 image_infos[i].os_type = llvm::Triple::IOS;
392 else if (os_name == "tvos")
393 image_infos[i].os_type = llvm::Triple::TvOS;
394 else if (os_name == "watchos")
395 image_infos[i].os_type = llvm::Triple::WatchOS;
Jason Molenda32762fd2018-10-11 00:28:35 +0000396 // NEED_BRIDGEOS_TRIPLE else if (os_name == "bridgeos")
397 // NEED_BRIDGEOS_TRIPLE image_infos[i].os_type = llvm::Triple::BridgeOS;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000398 }
399 if (image->HasKey("min_version_os_sdk")) {
400 image_infos[i].min_version_os_sdk =
401 image->GetValueForKey("min_version_os_sdk")
402 ->GetAsString()
403 ->GetValue();
Jason Molenda5fe4d142016-07-17 21:27:32 +0000404 }
405
Kate Stoneb9c1b512016-09-06 20:57:50 +0000406 // Fields that aren't used by DynamicLoaderDarwin so debugserver doesn't
Adrian Prantl05097242018-04-30 16:49:04 +0000407 // currently send them in the reply.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000408
409 if (mh->HasKey("flags"))
410 image_infos[i].header.flags =
411 mh->GetValueForKey("flags")->GetAsInteger()->GetValue();
412 else
413 image_infos[i].header.flags = 0;
414
415 if (mh->HasKey("ncmds"))
416 image_infos[i].header.ncmds =
417 mh->GetValueForKey("ncmds")->GetAsInteger()->GetValue();
418 else
419 image_infos[i].header.ncmds = 0;
420
421 if (mh->HasKey("sizeofcmds"))
422 image_infos[i].header.sizeofcmds =
423 mh->GetValueForKey("sizeofcmds")->GetAsInteger()->GetValue();
424 else
425 image_infos[i].header.sizeofcmds = 0;
426
427 StructuredData::Array *segments =
428 image->GetValueForKey("segments")->GetAsArray();
429 uint32_t segcount = segments->GetSize();
430 for (size_t j = 0; j < segcount; j++) {
431 Segment segment;
432 StructuredData::Dictionary *seg =
433 segments->GetItemAtIndex(j)->GetAsDictionary();
Zachary Turner28333212017-05-12 05:49:54 +0000434 segment.name =
435 ConstString(seg->GetValueForKey("name")->GetAsString()->GetValue());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000436 segment.vmaddr =
437 seg->GetValueForKey("vmaddr")->GetAsInteger()->GetValue();
438 segment.vmsize =
439 seg->GetValueForKey("vmsize")->GetAsInteger()->GetValue();
440 segment.fileoff =
441 seg->GetValueForKey("fileoff")->GetAsInteger()->GetValue();
442 segment.filesize =
443 seg->GetValueForKey("filesize")->GetAsInteger()->GetValue();
444 segment.maxprot =
445 seg->GetValueForKey("maxprot")->GetAsInteger()->GetValue();
446
447 // Fields that aren't used by DynamicLoaderDarwin so debugserver doesn't
Adrian Prantl05097242018-04-30 16:49:04 +0000448 // currently send them in the reply.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000449
450 if (seg->HasKey("initprot"))
451 segment.initprot =
452 seg->GetValueForKey("initprot")->GetAsInteger()->GetValue();
453 else
454 segment.initprot = 0;
455
456 if (seg->HasKey("flags"))
457 segment.flags =
458 seg->GetValueForKey("flags")->GetAsInteger()->GetValue();
459 else
460 segment.flags = 0;
461
462 if (seg->HasKey("nsects"))
463 segment.nsects =
464 seg->GetValueForKey("nsects")->GetAsInteger()->GetValue();
465 else
466 segment.nsects = 0;
467
468 image_infos[i].segments.push_back(segment);
469 }
470
Jim Inghamf3ecbfc2019-01-24 22:43:44 +0000471 image_infos[i].uuid.SetFromOptionalStringRef(
Zachary Turner28333212017-05-12 05:49:54 +0000472 image->GetValueForKey("uuid")->GetAsString()->GetValue());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000473
Adrian Prantl05097242018-04-30 16:49:04 +0000474 // All sections listed in the dyld image info structure will all either be
475 // fixed up already, or they will all be off by a single slide amount that
476 // is determined by finding the first segment that is at file offset zero
477 // which also has bytes (a file size that is greater than zero) in the
478 // object file.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000479
480 // Determine the slide amount (if any)
481 const size_t num_sections = image_infos[i].segments.size();
482 for (size_t k = 0; k < num_sections; ++k) {
Adrian Prantl05097242018-04-30 16:49:04 +0000483 // Iterate through the object file sections to find the first section
484 // that starts of file offset zero and that has bytes in the file...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000485 if ((image_infos[i].segments[k].fileoff == 0 &&
486 image_infos[i].segments[k].filesize > 0) ||
487 (image_infos[i].segments[k].name == ConstString("__TEXT"))) {
488 image_infos[i].slide =
489 image_infos[i].address - image_infos[i].segments[k].vmaddr;
Adrian Prantl05097242018-04-30 16:49:04 +0000490 // We have found the slide amount, so we can exit this for loop.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000491 break;
492 }
493 }
494 }
495
496 return true;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000497}
498
Kate Stoneb9c1b512016-09-06 20:57:50 +0000499void DynamicLoaderDarwin::UpdateSpecialBinariesFromNewImageInfos(
500 ImageInfo::collection &image_infos) {
501 uint32_t exe_idx = UINT32_MAX;
502 uint32_t dyld_idx = UINT32_MAX;
503 Target &target = m_process->GetTarget();
504 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
505 ConstString g_dyld_sim_filename("dyld_sim");
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000506
Kate Stoneb9c1b512016-09-06 20:57:50 +0000507 ArchSpec target_arch = target.GetArchitecture();
508 const size_t image_infos_size = image_infos.size();
509 for (size_t i = 0; i < image_infos_size; i++) {
510 if (image_infos[i].header.filetype == llvm::MachO::MH_DYLINKER) {
Jason Molenda32762fd2018-10-11 00:28:35 +0000511 // In a "simulator" process (an x86 process that is
512 // ios/tvos/watchos/bridgeos) we will have two dyld modules --
513 // a "dyld" that we want to keep track of, and a "dyld_sim" which
514 // we don't need to keep track of here. If the target is an x86
515 // system and the OS of the dyld binary is ios/tvos/watchos/bridgeos,
516 // then we are looking at dyld_sym.
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000517
Adrian Prantl05097242018-04-30 16:49:04 +0000518 // debugserver has only recently (late 2016) started sending up the os
519 // type for each binary it sees -- so if we don't have an os type, use a
520 // filename check as our next best guess.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000521 if (image_infos[i].os_type == llvm::Triple::OSType::UnknownOS) {
522 if (image_infos[i].file_spec.GetFilename() != g_dyld_sim_filename) {
523 dyld_idx = i;
524 }
525 } else if (target_arch.GetTriple().getArch() == llvm::Triple::x86 ||
526 target_arch.GetTriple().getArch() == llvm::Triple::x86_64) {
527 if (image_infos[i].os_type != llvm::Triple::OSType::IOS &&
528 image_infos[i].os_type != llvm::Triple::TvOS &&
529 image_infos[i].os_type != llvm::Triple::WatchOS) {
Jason Molenda32762fd2018-10-11 00:28:35 +0000530 // NEED_BRIDGEOS_TRIPLE image_infos[i].os_type != llvm::Triple::BridgeOS) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000531 dyld_idx = i;
532 }
533 }
Jason Molenda777fcec2017-01-21 01:17:36 +0000534 else {
Adrian Prantl05097242018-04-30 16:49:04 +0000535 // catch-all for any other environment -- trust that dyld is actually
536 // dyld
Jason Molenda777fcec2017-01-21 01:17:36 +0000537 dyld_idx = i;
538 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000539 } else if (image_infos[i].header.filetype == llvm::MachO::MH_EXECUTE) {
540 exe_idx = i;
541 }
542 }
543
544 if (exe_idx != UINT32_MAX) {
545 const bool can_create = true;
546 ModuleSP exe_module_sp(
547 FindTargetModuleForImageInfo(image_infos[exe_idx], can_create, NULL));
548 if (exe_module_sp) {
549 if (log)
550 log->Printf("Found executable module: %s",
551 exe_module_sp->GetFileSpec().GetPath().c_str());
552 target.GetImages().AppendIfNeeded(exe_module_sp);
553 UpdateImageLoadAddress(exe_module_sp.get(), image_infos[exe_idx]);
554 if (exe_module_sp.get() != target.GetExecutableModulePointer()) {
Jonas Devliegheref9a07e92018-09-20 09:09:05 +0000555 target.SetExecutableModule(exe_module_sp, eLoadDependentsNo);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000556 }
557 }
558 }
559
560 if (dyld_idx != UINT32_MAX) {
561 const bool can_create = true;
562 ModuleSP dyld_sp =
563 FindTargetModuleForImageInfo(image_infos[dyld_idx], can_create, NULL);
564 if (dyld_sp.get()) {
565 if (log)
566 log->Printf("Found dyld module: %s",
567 dyld_sp->GetFileSpec().GetPath().c_str());
568 target.GetImages().AppendIfNeeded(dyld_sp);
569 UpdateImageLoadAddress(dyld_sp.get(), image_infos[dyld_idx]);
570 SetDYLDModule(dyld_sp);
571 }
572 }
573}
574
575void DynamicLoaderDarwin::UpdateDYLDImageInfoFromNewImageInfo(
576 ImageInfo &image_info) {
577 if (image_info.header.filetype == llvm::MachO::MH_DYLINKER) {
578 const bool can_create = true;
579 ModuleSP dyld_sp =
580 FindTargetModuleForImageInfo(image_info, can_create, NULL);
581 if (dyld_sp.get()) {
582 Target &target = m_process->GetTarget();
583 target.GetImages().AppendIfNeeded(dyld_sp);
584 UpdateImageLoadAddress(dyld_sp.get(), image_info);
585 SetDYLDModule(dyld_sp);
586 }
587 }
588}
589
590void DynamicLoaderDarwin::SetDYLDModule(lldb::ModuleSP &dyld_module_sp) {
591 m_dyld_module_wp = dyld_module_sp;
592}
593
594ModuleSP DynamicLoaderDarwin::GetDYLDModule() {
595 ModuleSP dyld_sp(m_dyld_module_wp.lock());
596 return dyld_sp;
597}
598
599bool DynamicLoaderDarwin::AddModulesUsingImageInfos(
600 ImageInfo::collection &image_infos) {
601 std::lock_guard<std::recursive_mutex> guard(m_mutex);
602 // Now add these images to the main list.
603 ModuleList loaded_module_list;
604 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
605 Target &target = m_process->GetTarget();
606 ModuleList &target_images = target.GetImages();
607
608 for (uint32_t idx = 0; idx < image_infos.size(); ++idx) {
609 if (log) {
610 log->Printf("Adding new image at address=0x%16.16" PRIx64 ".",
611 image_infos[idx].address);
612 image_infos[idx].PutToLog(log);
613 }
614
615 m_dyld_image_infos.push_back(image_infos[idx]);
616
617 ModuleSP image_module_sp(
618 FindTargetModuleForImageInfo(image_infos[idx], true, NULL));
619
620 if (image_module_sp) {
621 ObjectFile *objfile = image_module_sp->GetObjectFile();
622 if (objfile) {
623 SectionList *sections = objfile->GetSectionList();
624 if (sections) {
625 ConstString commpage_dbstr("__commpage");
626 Section *commpage_section =
627 sections->FindSectionByName(commpage_dbstr).get();
628 if (commpage_section) {
629 ModuleSpec module_spec(objfile->GetFileSpec(),
630 image_infos[idx].GetArchitecture());
631 module_spec.GetObjectName() = commpage_dbstr;
632 ModuleSP commpage_image_module_sp(
633 target_images.FindFirstModule(module_spec));
634 if (!commpage_image_module_sp) {
635 module_spec.SetObjectOffset(objfile->GetFileOffset() +
636 commpage_section->GetFileOffset());
637 module_spec.SetObjectSize(objfile->GetByteSize());
638 commpage_image_module_sp = target.GetSharedModule(module_spec);
639 if (!commpage_image_module_sp ||
640 commpage_image_module_sp->GetObjectFile() == NULL) {
641 commpage_image_module_sp = m_process->ReadModuleFromMemory(
642 image_infos[idx].file_spec, image_infos[idx].address);
643 // Always load a memory image right away in the target in case
644 // we end up trying to read the symbol table from memory... The
645 // __LINKEDIT will need to be mapped so we can figure out where
646 // the symbol table bits are...
647 bool changed = false;
648 UpdateImageLoadAddress(commpage_image_module_sp.get(),
649 image_infos[idx]);
650 target.GetImages().Append(commpage_image_module_sp);
651 if (changed) {
652 image_infos[idx].load_stop_id = m_process->GetStopID();
653 loaded_module_list.AppendIfNeeded(commpage_image_module_sp);
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000654 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000655 }
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000656 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000657 }
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000658 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000659 }
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000660
Adrian Prantl05097242018-04-30 16:49:04 +0000661 // UpdateImageLoadAddress will return true if any segments change load
662 // address. We need to check this so we don't mention that all loaded
663 // shared libraries are newly loaded each time we hit out dyld breakpoint
664 // since dyld will list all shared libraries each time.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000665 if (UpdateImageLoadAddress(image_module_sp.get(), image_infos[idx])) {
666 target_images.AppendIfNeeded(image_module_sp);
667 loaded_module_list.AppendIfNeeded(image_module_sp);
668 }
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000669 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000670 }
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000671
Kate Stoneb9c1b512016-09-06 20:57:50 +0000672 if (loaded_module_list.GetSize() > 0) {
673 if (log)
674 loaded_module_list.LogUUIDAndPaths(log,
675 "DynamicLoaderDarwin::ModulesDidLoad");
676 m_process->GetTarget().ModulesDidLoad(loaded_module_list);
677 }
678 return true;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000679}
680
Jason Molenda5fe4d142016-07-17 21:27:32 +0000681//----------------------------------------------------------------------
682// On Mac OS X libobjc (the Objective-C runtime) has several critical dispatch
Adrian Prantl05097242018-04-30 16:49:04 +0000683// functions written in hand-written assembly, and also have hand-written
684// unwind information in the eh_frame section. Normally we prefer analyzing
685// the assembly instructions of a currently executing frame to unwind from that
686// frame -- but on hand-written functions this profiling can fail. We should
687// use the eh_frame instructions for these functions all the time.
Jason Molenda5fe4d142016-07-17 21:27:32 +0000688//
689// As an aside, it would be better if the eh_frame entries had a flag (or were
690// extensible so they could have an Apple-specific flag) which indicates that
691// the instructions are asynchronous -- accurate at every instruction, instead
692// of our normal default assumption that they are not.
693//----------------------------------------------------------------------
694
Kate Stoneb9c1b512016-09-06 20:57:50 +0000695bool DynamicLoaderDarwin::AlwaysRelyOnEHUnwindInfo(SymbolContext &sym_ctx) {
696 ModuleSP module_sp;
697 if (sym_ctx.symbol) {
698 module_sp = sym_ctx.symbol->GetAddressRef().GetModule();
699 }
700 if (module_sp.get() == NULL && sym_ctx.function) {
701 module_sp =
702 sym_ctx.function->GetAddressRange().GetBaseAddress().GetModule();
703 }
704 if (module_sp.get() == NULL)
Jason Molenda5fe4d142016-07-17 21:27:32 +0000705 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000706
707 ObjCLanguageRuntime *objc_runtime = m_process->GetObjCLanguageRuntime();
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000708 return objc_runtime != NULL && objc_runtime->IsModuleObjCLibrary(module_sp);
Jason Molenda5fe4d142016-07-17 21:27:32 +0000709}
710
Jason Molenda5fe4d142016-07-17 21:27:32 +0000711//----------------------------------------------------------------------
712// Dump a Segment to the file handle provided.
713//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000714void DynamicLoaderDarwin::Segment::PutToLog(Log *log,
715 lldb::addr_t slide) const {
716 if (log) {
717 if (slide == 0)
718 log->Printf("\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ")",
719 name.AsCString(""), vmaddr + slide, vmaddr + slide + vmsize);
720 else
721 log->Printf("\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64
722 ") slide = 0x%" PRIx64,
723 name.AsCString(""), vmaddr + slide, vmaddr + slide + vmsize,
724 slide);
725 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000726}
727
728const DynamicLoaderDarwin::Segment *
Kate Stoneb9c1b512016-09-06 20:57:50 +0000729DynamicLoaderDarwin::ImageInfo::FindSegment(const ConstString &name) const {
730 const size_t num_segments = segments.size();
731 for (size_t i = 0; i < num_segments; ++i) {
732 if (segments[i].name == name)
733 return &segments[i];
734 }
735 return NULL;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000736}
737
Jason Molenda5fe4d142016-07-17 21:27:32 +0000738//----------------------------------------------------------------------
739// Dump an image info structure to the file handle provided.
740//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000741void DynamicLoaderDarwin::ImageInfo::PutToLog(Log *log) const {
Pavel Labathfbb14282018-06-20 20:13:04 +0000742 if (!log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000743 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000744 if (address == LLDB_INVALID_ADDRESS) {
Pavel Labathfbb14282018-06-20 20:13:04 +0000745 LLDB_LOG(log, "modtime={0:x+8} uuid={1} path='{2}' (UNLOADED)", mod_date,
746 uuid.GetAsString(), file_spec.GetPath());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000747 } else {
Pavel Labathfbb14282018-06-20 20:13:04 +0000748 LLDB_LOG(log, "address={0:x+16} modtime={1:x+8} uuid={2} path='{3}'",
749 address, mod_date, uuid.GetAsString(), file_spec.GetPath());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000750 for (uint32_t i = 0; i < segments.size(); ++i)
751 segments[i].PutToLog(log, slide);
752 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000753}
754
Kate Stoneb9c1b512016-09-06 20:57:50 +0000755void DynamicLoaderDarwin::PrivateInitialize(Process *process) {
756 DEBUG_PRINTF("DynamicLoaderDarwin::%s() process state = %s\n", __FUNCTION__,
757 StateAsCString(m_process->GetState()));
758 Clear(true);
759 m_process = process;
760 m_process->GetTarget().ClearAllLoadedSections();
Jason Molenda5fe4d142016-07-17 21:27:32 +0000761}
762
763//----------------------------------------------------------------------
764// Member function that gets called when the process state changes.
765//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000766void DynamicLoaderDarwin::PrivateProcessStateChanged(Process *process,
767 StateType state) {
768 DEBUG_PRINTF("DynamicLoaderDarwin::%s(%s)\n", __FUNCTION__,
769 StateAsCString(state));
770 switch (state) {
771 case eStateConnected:
772 case eStateAttaching:
773 case eStateLaunching:
774 case eStateInvalid:
775 case eStateUnloaded:
776 case eStateExited:
777 case eStateDetached:
778 Clear(false);
779 break;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000780
Kate Stoneb9c1b512016-09-06 20:57:50 +0000781 case eStateStopped:
Adrian Prantl05097242018-04-30 16:49:04 +0000782 // Keep trying find dyld and set our notification breakpoint each time we
783 // stop until we succeed
Kate Stoneb9c1b512016-09-06 20:57:50 +0000784 if (!DidSetNotificationBreakpoint() && m_process->IsAlive()) {
785 if (NeedToDoInitialImageFetch())
786 DoInitialImageFetch();
Jason Molenda5fe4d142016-07-17 21:27:32 +0000787
Kate Stoneb9c1b512016-09-06 20:57:50 +0000788 SetNotificationBreakpoint();
Jason Molenda5fe4d142016-07-17 21:27:32 +0000789 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000790 break;
791
792 case eStateRunning:
793 case eStateStepping:
794 case eStateCrashed:
795 case eStateSuspended:
796 break;
797 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000798}
799
800ThreadPlanSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000801DynamicLoaderDarwin::GetStepThroughTrampolinePlan(Thread &thread,
802 bool stop_others) {
803 ThreadPlanSP thread_plan_sp;
804 StackFrame *current_frame = thread.GetStackFrameAtIndex(0).get();
805 const SymbolContext &current_context =
806 current_frame->GetSymbolContext(eSymbolContextSymbol);
807 Symbol *current_symbol = current_context.symbol;
808 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
809 TargetSP target_sp(thread.CalculateTarget());
Jason Molenda5fe4d142016-07-17 21:27:32 +0000810
Kate Stoneb9c1b512016-09-06 20:57:50 +0000811 if (current_symbol != NULL) {
812 std::vector<Address> addresses;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000813
Kate Stoneb9c1b512016-09-06 20:57:50 +0000814 if (current_symbol->IsTrampoline()) {
815 const ConstString &trampoline_name = current_symbol->GetMangled().GetName(
816 current_symbol->GetLanguage(), Mangled::ePreferMangled);
Jason Molenda5fe4d142016-07-17 21:27:32 +0000817
Kate Stoneb9c1b512016-09-06 20:57:50 +0000818 if (trampoline_name) {
819 const ModuleList &images = target_sp->GetImages();
820
821 SymbolContextList code_symbols;
822 images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeCode,
823 code_symbols);
824 size_t num_code_symbols = code_symbols.GetSize();
825
826 if (num_code_symbols > 0) {
827 for (uint32_t i = 0; i < num_code_symbols; i++) {
828 SymbolContext context;
829 AddressRange addr_range;
830 if (code_symbols.GetContextAtIndex(i, context)) {
831 context.GetAddressRange(eSymbolContextEverything, 0, false,
832 addr_range);
833 addresses.push_back(addr_range.GetBaseAddress());
834 if (log) {
835 addr_t load_addr =
836 addr_range.GetBaseAddress().GetLoadAddress(target_sp.get());
837
838 log->Printf("Found a trampoline target symbol at 0x%" PRIx64
839 ".",
840 load_addr);
841 }
842 }
843 }
844 }
845
846 SymbolContextList reexported_symbols;
847 images.FindSymbolsWithNameAndType(
848 trampoline_name, eSymbolTypeReExported, reexported_symbols);
849 size_t num_reexported_symbols = reexported_symbols.GetSize();
850 if (num_reexported_symbols > 0) {
851 for (uint32_t i = 0; i < num_reexported_symbols; i++) {
852 SymbolContext context;
853 if (reexported_symbols.GetContextAtIndex(i, context)) {
854 if (context.symbol) {
855 Symbol *actual_symbol =
856 context.symbol->ResolveReExportedSymbol(*target_sp.get());
857 if (actual_symbol) {
858 const Address actual_symbol_addr =
859 actual_symbol->GetAddress();
860 if (actual_symbol_addr.IsValid()) {
861 addresses.push_back(actual_symbol_addr);
862 if (log) {
863 lldb::addr_t load_addr =
864 actual_symbol_addr.GetLoadAddress(target_sp.get());
865 log->Printf(
866 "Found a re-exported symbol: %s at 0x%" PRIx64 ".",
867 actual_symbol->GetName().GetCString(), load_addr);
Jason Molenda5fe4d142016-07-17 21:27:32 +0000868 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000869 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000870 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000871 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000872 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000873 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000874 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000875
876 SymbolContextList indirect_symbols;
877 images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeResolver,
878 indirect_symbols);
879 size_t num_indirect_symbols = indirect_symbols.GetSize();
880 if (num_indirect_symbols > 0) {
881 for (uint32_t i = 0; i < num_indirect_symbols; i++) {
882 SymbolContext context;
883 AddressRange addr_range;
884 if (indirect_symbols.GetContextAtIndex(i, context)) {
885 context.GetAddressRange(eSymbolContextEverything, 0, false,
886 addr_range);
887 addresses.push_back(addr_range.GetBaseAddress());
888 if (log) {
889 addr_t load_addr =
890 addr_range.GetBaseAddress().GetLoadAddress(target_sp.get());
891
892 log->Printf("Found an indirect target symbol at 0x%" PRIx64 ".",
893 load_addr);
894 }
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 }
899 } else if (current_symbol->GetType() == eSymbolTypeReExported) {
900 // I am not sure we could ever end up stopped AT a re-exported symbol.
901 // But just in case:
902
903 const Symbol *actual_symbol =
904 current_symbol->ResolveReExportedSymbol(*(target_sp.get()));
905 if (actual_symbol) {
906 Address target_addr(actual_symbol->GetAddress());
907 if (target_addr.IsValid()) {
908 if (log)
909 log->Printf(
910 "Found a re-exported symbol: %s pointing to: %s at 0x%" PRIx64
911 ".",
912 current_symbol->GetName().GetCString(),
913 actual_symbol->GetName().GetCString(),
914 target_addr.GetLoadAddress(target_sp.get()));
915 addresses.push_back(target_addr.GetLoadAddress(target_sp.get()));
Jason Molenda5fe4d142016-07-17 21:27:32 +0000916 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000917 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000918 }
919
Kate Stoneb9c1b512016-09-06 20:57:50 +0000920 if (addresses.size() > 0) {
Adrian Prantl05097242018-04-30 16:49:04 +0000921 // First check whether any of the addresses point to Indirect symbols,
922 // and if they do, resolve them:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000923 std::vector<lldb::addr_t> load_addrs;
924 for (Address address : addresses) {
925 Symbol *symbol = address.CalculateSymbolContextSymbol();
926 if (symbol && symbol->IsIndirect()) {
Zachary Turner97206d52017-05-12 04:51:55 +0000927 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000928 Address symbol_address = symbol->GetAddress();
929 addr_t resolved_addr = thread.GetProcess()->ResolveIndirectFunction(
930 &symbol_address, error);
931 if (error.Success()) {
932 load_addrs.push_back(resolved_addr);
933 if (log)
934 log->Printf("ResolveIndirectFunction found resolved target for "
935 "%s at 0x%" PRIx64 ".",
936 symbol->GetName().GetCString(), resolved_addr);
937 }
938 } else {
939 load_addrs.push_back(address.GetLoadAddress(target_sp.get()));
Jason Molenda5fe4d142016-07-17 21:27:32 +0000940 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000941 }
942 thread_plan_sp.reset(
943 new ThreadPlanRunToAddress(thread, load_addrs, stop_others));
Jason Molenda5fe4d142016-07-17 21:27:32 +0000944 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000945 } else {
946 if (log)
947 log->Printf("Could not find symbol for step through.");
948 }
949
950 return thread_plan_sp;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000951}
952
Kate Stoneb9c1b512016-09-06 20:57:50 +0000953size_t DynamicLoaderDarwin::FindEquivalentSymbols(
954 lldb_private::Symbol *original_symbol, lldb_private::ModuleList &images,
955 lldb_private::SymbolContextList &equivalent_symbols) {
956 const ConstString &trampoline_name = original_symbol->GetMangled().GetName(
957 original_symbol->GetLanguage(), Mangled::ePreferMangled);
958 if (!trampoline_name)
959 return 0;
960
961 size_t initial_size = equivalent_symbols.GetSize();
962
963 static const char *resolver_name_regex = "(_gc|_non_gc|\\$[A-Za-z0-9\\$]+)$";
964 std::string equivalent_regex_buf("^");
965 equivalent_regex_buf.append(trampoline_name.GetCString());
966 equivalent_regex_buf.append(resolver_name_regex);
967
Zachary Turner95eae422016-09-21 16:01:28 +0000968 RegularExpression equivalent_name_regex(equivalent_regex_buf);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000969 const bool append = true;
970 images.FindSymbolsMatchingRegExAndType(equivalent_name_regex, eSymbolTypeCode,
971 equivalent_symbols, append);
972
973 return equivalent_symbols.GetSize() - initial_size;
974}
975
976lldb::ModuleSP DynamicLoaderDarwin::GetPThreadLibraryModule() {
977 ModuleSP module_sp = m_libpthread_module_wp.lock();
978 if (!module_sp) {
979 SymbolContextList sc_list;
980 ModuleSpec module_spec;
981 module_spec.GetFileSpec().GetFilename().SetCString(
982 "libsystem_pthread.dylib");
983 ModuleList module_list;
984 if (m_process->GetTarget().GetImages().FindModules(module_spec,
985 module_list)) {
986 if (module_list.GetSize() == 1) {
987 module_sp = module_list.GetModuleAtIndex(0);
Jason Molenda5fe4d142016-07-17 21:27:32 +0000988 if (module_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000989 m_libpthread_module_wp = module_sp;
990 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000991 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000992 }
993 return module_sp;
994}
995
996Address DynamicLoaderDarwin::GetPthreadSetSpecificAddress() {
997 if (!m_pthread_getspecific_addr.IsValid()) {
998 ModuleSP module_sp = GetPThreadLibraryModule();
999 if (module_sp) {
1000 lldb_private::SymbolContextList sc_list;
1001 module_sp->FindSymbolsWithNameAndType(ConstString("pthread_getspecific"),
1002 eSymbolTypeCode, sc_list);
1003 SymbolContext sc;
1004 if (sc_list.GetContextAtIndex(0, sc)) {
1005 if (sc.symbol)
1006 m_pthread_getspecific_addr = sc.symbol->GetAddress();
1007 }
1008 }
1009 }
1010 return m_pthread_getspecific_addr;
Jason Molenda5fe4d142016-07-17 21:27:32 +00001011}
1012
1013lldb::addr_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001014DynamicLoaderDarwin::GetThreadLocalData(const lldb::ModuleSP module_sp,
1015 const lldb::ThreadSP thread_sp,
1016 lldb::addr_t tls_file_addr) {
1017 if (!thread_sp || !module_sp)
Jason Molenda5fe4d142016-07-17 21:27:32 +00001018 return LLDB_INVALID_ADDRESS;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001019
1020 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1021
1022 const uint32_t addr_size = m_process->GetAddressByteSize();
1023 uint8_t buf[sizeof(lldb::addr_t) * 3];
1024
1025 lldb_private::Address tls_addr;
1026 if (module_sp->ResolveFileAddress(tls_file_addr, tls_addr)) {
Zachary Turner97206d52017-05-12 04:51:55 +00001027 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001028 const size_t tsl_data_size = addr_size * 3;
1029 Target &target = m_process->GetTarget();
1030 if (target.ReadMemory(tls_addr, false, buf, tsl_data_size, error) ==
1031 tsl_data_size) {
1032 const ByteOrder byte_order = m_process->GetByteOrder();
1033 DataExtractor data(buf, sizeof(buf), byte_order, addr_size);
1034 lldb::offset_t offset = addr_size; // Skip the first pointer
1035 const lldb::addr_t pthread_key = data.GetAddress(&offset);
1036 const lldb::addr_t tls_offset = data.GetAddress(&offset);
1037 if (pthread_key != 0) {
Adrian Prantl05097242018-04-30 16:49:04 +00001038 // First check to see if we have already figured out the location of
1039 // TLS data for the pthread_key on a specific thread yet. If we have we
1040 // can re-use it since its location will not change unless the process
1041 // execs.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001042 const tid_t tid = thread_sp->GetID();
1043 auto tid_pos = m_tid_to_tls_map.find(tid);
1044 if (tid_pos != m_tid_to_tls_map.end()) {
1045 auto tls_pos = tid_pos->second.find(pthread_key);
1046 if (tls_pos != tid_pos->second.end()) {
1047 return tls_pos->second + tls_offset;
1048 }
1049 }
1050 StackFrameSP frame_sp = thread_sp->GetStackFrameAtIndex(0);
1051 if (frame_sp) {
1052 ClangASTContext *clang_ast_context =
1053 target.GetScratchClangASTContext();
1054
1055 if (!clang_ast_context)
1056 return LLDB_INVALID_ADDRESS;
1057
1058 CompilerType clang_void_ptr_type =
1059 clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
1060 Address pthread_getspecific_addr = GetPthreadSetSpecificAddress();
1061 if (pthread_getspecific_addr.IsValid()) {
1062 EvaluateExpressionOptions options;
1063
1064 lldb::ThreadPlanSP thread_plan_sp(new ThreadPlanCallFunction(
1065 *thread_sp, pthread_getspecific_addr, clang_void_ptr_type,
1066 llvm::ArrayRef<lldb::addr_t>(pthread_key), options));
1067
1068 DiagnosticManager execution_errors;
1069 ExecutionContext exe_ctx(thread_sp);
1070 lldb::ExpressionResults results = m_process->RunThreadPlan(
1071 exe_ctx, thread_plan_sp, options, execution_errors);
1072
1073 if (results == lldb::eExpressionCompleted) {
1074 lldb::ValueObjectSP result_valobj_sp =
1075 thread_plan_sp->GetReturnValueObject();
1076 if (result_valobj_sp) {
1077 const lldb::addr_t pthread_key_data =
1078 result_valobj_sp->GetValueAsUnsigned(0);
1079 if (pthread_key_data) {
1080 m_tid_to_tls_map[tid].insert(
1081 std::make_pair(pthread_key, pthread_key_data));
1082 return pthread_key_data + tls_offset;
1083 }
1084 }
1085 }
1086 }
1087 }
1088 }
1089 }
1090 }
1091 return LLDB_INVALID_ADDRESS;
Jason Molenda5fe4d142016-07-17 21:27:32 +00001092}
1093
Kate Stoneb9c1b512016-09-06 20:57:50 +00001094bool DynamicLoaderDarwin::UseDYLDSPI(Process *process) {
1095 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001096 bool use_new_spi_interface = false;
Jason Molenda9ab5dc22016-07-21 08:30:55 +00001097
Pavel Labath2272c482018-06-18 15:02:23 +00001098 llvm::VersionTuple version = process->GetHostOSVersion();
1099 if (!version.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001100 const llvm::Triple::OSType os_type =
1101 process->GetTarget().GetArchitecture().GetTriple().getOS();
Jason Molenda9ab5dc22016-07-21 08:30:55 +00001102
Kate Stoneb9c1b512016-09-06 20:57:50 +00001103 // macOS 10.12 and newer
1104 if (os_type == llvm::Triple::MacOSX &&
Pavel Labath2272c482018-06-18 15:02:23 +00001105 version >= llvm::VersionTuple(10, 12))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001106 use_new_spi_interface = true;
Jason Molenda9ab5dc22016-07-21 08:30:55 +00001107
Kate Stoneb9c1b512016-09-06 20:57:50 +00001108 // iOS 10 and newer
Pavel Labath2272c482018-06-18 15:02:23 +00001109 if (os_type == llvm::Triple::IOS && version >= llvm::VersionTuple(10))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001110 use_new_spi_interface = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001111
1112 // tvOS 10 and newer
Pavel Labath2272c482018-06-18 15:02:23 +00001113 if (os_type == llvm::Triple::TvOS && version >= llvm::VersionTuple(10))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001114 use_new_spi_interface = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001115
1116 // watchOS 3 and newer
Pavel Labath2272c482018-06-18 15:02:23 +00001117 if (os_type == llvm::Triple::WatchOS && version >= llvm::VersionTuple(3))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001118 use_new_spi_interface = true;
Jason Molenda32762fd2018-10-11 00:28:35 +00001119
1120 // NEED_BRIDGEOS_TRIPLE // Any BridgeOS
1121 // NEED_BRIDGEOS_TRIPLE if (os_type == llvm::Triple::BridgeOS)
1122 // NEED_BRIDGEOS_TRIPLE use_new_spi_interface = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001123 }
1124
Kate Stoneb9c1b512016-09-06 20:57:50 +00001125 if (log) {
1126 if (use_new_spi_interface)
1127 log->Printf(
1128 "DynamicLoaderDarwin::UseDYLDSPI: Use new DynamicLoader plugin");
1129 else
1130 log->Printf(
1131 "DynamicLoaderDarwin::UseDYLDSPI: Use old DynamicLoader plugin");
1132 }
1133 return use_new_spi_interface;
Jason Molenda9ab5dc22016-07-21 08:30:55 +00001134}