blob: 944be9633e00e020e8a4697dbdad5b9515bf99c0 [file] [log] [blame]
Jason Molenda5fe4d142016-07-17 21:27:32 +00001//===-- DynamicLoaderDarwin.cpp -----------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Pavel Labath1408bf72016-11-01 16:11:14 +000010#include "DynamicLoaderDarwin.h"
11
Jason Molenda5fe4d142016-07-17 21:27:32 +000012#include "lldb/Breakpoint/StoppointCallbackContext.h"
Jason Molenda5fe4d142016-07-17 21:27:32 +000013#include "lldb/Core/Debugger.h"
Jason Molenda5fe4d142016-07-17 21:27:32 +000014#include "lldb/Core/Module.h"
15#include "lldb/Core/ModuleSpec.h"
16#include "lldb/Core/PluginManager.h"
17#include "lldb/Core/Section.h"
Jason Molenda5fe4d142016-07-17 21:27:32 +000018#include "lldb/Expression/DiagnosticManager.h"
Pavel Labath1408bf72016-11-01 16:11:14 +000019#include "lldb/Host/FileSystem.h"
Jason Molenda5fe4d142016-07-17 21:27:32 +000020#include "lldb/Symbol/ClangASTContext.h"
21#include "lldb/Symbol/Function.h"
22#include "lldb/Symbol/ObjectFile.h"
23#include "lldb/Target/ABI.h"
24#include "lldb/Target/ObjCLanguageRuntime.h"
25#include "lldb/Target/RegisterContext.h"
26#include "lldb/Target/StackFrame.h"
27#include "lldb/Target/Target.h"
28#include "lldb/Target/Thread.h"
29#include "lldb/Target/ThreadPlanCallFunction.h"
30#include "lldb/Target/ThreadPlanRunToAddress.h"
Zachary Turner666cc0b2017-03-04 01:30:05 +000031#include "lldb/Utility/DataBuffer.h"
32#include "lldb/Utility/DataBufferHeap.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000033#include "lldb/Utility/Log.h"
Pavel Labathd821c992018-08-07 11:07:21 +000034#include "lldb/Utility/State.h"
Jason Molenda5fe4d142016-07-17 21:27:32 +000035
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
50using namespace lldb;
51using namespace lldb_private;
52
Jason Molenda5fe4d142016-07-17 21:27:32 +000053//----------------------------------------------------------------------
54// Constructor
55//----------------------------------------------------------------------
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
61//----------------------------------------------------------------------
62// Destructor
63//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +000064DynamicLoaderDarwin::~DynamicLoaderDarwin() {}
65
66//------------------------------------------------------------------
67/// Called after attaching a process.
68///
69/// Allow DynamicLoader plug-ins to execute some code after
70/// attaching to a process.
71//------------------------------------------------------------------
72void DynamicLoaderDarwin::DidAttach() {
73 PrivateInitialize(m_process);
74 DoInitialImageFetch();
75 SetNotificationBreakpoint();
Jason Molenda5fe4d142016-07-17 21:27:32 +000076}
77
78//------------------------------------------------------------------
79/// Called after attaching a process.
80///
81/// Allow DynamicLoader plug-ins to execute some code after
82/// attaching to a process.
83//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +000084void DynamicLoaderDarwin::DidLaunch() {
85 PrivateInitialize(m_process);
86 DoInitialImageFetch();
87 SetNotificationBreakpoint();
Jason Molenda5fe4d142016-07-17 21:27:32 +000088}
89
Jason Molenda5fe4d142016-07-17 21:27:32 +000090//----------------------------------------------------------------------
91// Clear out the state of this class.
92//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +000093void DynamicLoaderDarwin::Clear(bool clear_process) {
94 std::lock_guard<std::recursive_mutex> guard(m_mutex);
95 if (clear_process)
96 m_process = NULL;
97 m_dyld_image_infos.clear();
98 m_dyld_image_infos_stop_id = UINT32_MAX;
99 m_dyld.Clear(false);
Jason Molenda5fe4d142016-07-17 21:27:32 +0000100}
101
Kate Stoneb9c1b512016-09-06 20:57:50 +0000102ModuleSP DynamicLoaderDarwin::FindTargetModuleForImageInfo(
103 ImageInfo &image_info, bool can_create, bool *did_create_ptr) {
104 if (did_create_ptr)
105 *did_create_ptr = false;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000106
Kate Stoneb9c1b512016-09-06 20:57:50 +0000107 Target &target = m_process->GetTarget();
108 const ModuleList &target_images = target.GetImages();
109 ModuleSpec module_spec(image_info.file_spec);
110 module_spec.GetUUID() = image_info.uuid;
111 ModuleSP module_sp(target_images.FindFirstModule(module_spec));
Jason Molenda5fe4d142016-07-17 21:27:32 +0000112
Kate Stoneb9c1b512016-09-06 20:57:50 +0000113 if (module_sp && !module_spec.GetUUID().IsValid() &&
114 !module_sp->GetUUID().IsValid()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000115 // No UUID, we must rely upon the cached module modification time and the
116 // modification time of the file on disk
Kate Stoneb9c1b512016-09-06 20:57:50 +0000117 if (module_sp->GetModificationTime() !=
Jonas Devlieghere46376962018-10-31 21:49:27 +0000118 FileSystem::Instance().GetModificationTime(module_sp->GetFileSpec()))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000119 module_sp.reset();
120 }
121
122 if (!module_sp) {
123 if (can_create) {
124 module_sp = target.GetSharedModule(module_spec);
125 if (!module_sp || module_sp->GetObjectFile() == NULL)
126 module_sp = m_process->ReadModuleFromMemory(image_info.file_spec,
127 image_info.address);
128
129 if (did_create_ptr)
130 *did_create_ptr = (bool)module_sp;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000131 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000132 }
133 return module_sp;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000134}
135
Kate Stoneb9c1b512016-09-06 20:57:50 +0000136void DynamicLoaderDarwin::UnloadImages(
137 const std::vector<lldb::addr_t> &solib_addresses) {
138 std::lock_guard<std::recursive_mutex> guard(m_mutex);
139 if (m_process->GetStopID() == m_dyld_image_infos_stop_id)
140 return;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000141
Kate Stoneb9c1b512016-09-06 20:57:50 +0000142 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
143 Target &target = m_process->GetTarget();
144 if (log)
145 log->Printf("Removing %" PRId64 " modules.",
146 (uint64_t)solib_addresses.size());
Jason Molenda5fe4d142016-07-17 21:27:32 +0000147
Kate Stoneb9c1b512016-09-06 20:57:50 +0000148 ModuleList unloaded_module_list;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000149
Kate Stoneb9c1b512016-09-06 20:57:50 +0000150 for (addr_t solib_addr : solib_addresses) {
151 Address header;
152 if (header.SetLoadAddress(solib_addr, &target)) {
153 if (header.GetOffset() == 0) {
154 ModuleSP module_to_remove(header.GetModule());
155 if (module_to_remove.get()) {
156 if (log)
157 log->Printf("Removing module at address 0x%" PRIx64, solib_addr);
158 // remove the sections from the Target
159 UnloadSections(module_to_remove);
160 // add this to the list of modules to remove
161 unloaded_module_list.AppendIfNeeded(module_to_remove);
162 // remove the entry from the m_dyld_image_infos
163 ImageInfo::collection::iterator pos, end = m_dyld_image_infos.end();
164 for (pos = m_dyld_image_infos.begin(); pos != end; pos++) {
165 if (solib_addr == (*pos).address) {
166 m_dyld_image_infos.erase(pos);
167 break;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000168 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000169 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000170 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000171 }
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 if (unloaded_module_list.GetSize() > 0) {
176 if (log) {
177 log->PutCString("Unloaded:");
178 unloaded_module_list.LogUUIDAndPaths(
179 log, "DynamicLoaderDarwin::UnloadModules");
Jason Molenda5fe4d142016-07-17 21:27:32 +0000180 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000181 m_process->GetTarget().GetImages().Remove(unloaded_module_list);
182 m_dyld_image_infos_stop_id = m_process->GetStopID();
183 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000184}
185
Kate Stoneb9c1b512016-09-06 20:57:50 +0000186void DynamicLoaderDarwin::UnloadAllImages() {
187 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
188 ModuleList unloaded_modules_list;
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000189
Kate Stoneb9c1b512016-09-06 20:57:50 +0000190 Target &target = m_process->GetTarget();
191 const ModuleList &target_modules = target.GetImages();
192 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000193
Kate Stoneb9c1b512016-09-06 20:57:50 +0000194 size_t num_modules = target_modules.GetSize();
195 ModuleSP dyld_sp(GetDYLDModule());
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000196
Kate Stoneb9c1b512016-09-06 20:57:50 +0000197 for (size_t i = 0; i < num_modules; i++) {
198 ModuleSP module_sp = target_modules.GetModuleAtIndexUnlocked(i);
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000199
Kate Stoneb9c1b512016-09-06 20:57:50 +0000200 // Don't remove dyld - else we'll lose our breakpoint notifying us about
Adrian Prantl05097242018-04-30 16:49:04 +0000201 // libraries being re-loaded...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000202 if (module_sp.get() != nullptr && module_sp.get() != dyld_sp.get()) {
203 UnloadSections(module_sp);
204 unloaded_modules_list.Append(module_sp);
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000205 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000206 }
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000207
Kate Stoneb9c1b512016-09-06 20:57:50 +0000208 if (unloaded_modules_list.GetSize() != 0) {
209 if (log) {
210 log->PutCString("Unloaded:");
211 unloaded_modules_list.LogUUIDAndPaths(
212 log, "DynamicLoaderDarwin::UnloadAllImages");
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000213 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000214 target.GetImages().Remove(unloaded_modules_list);
215 m_dyld_image_infos.clear();
216 m_dyld_image_infos_stop_id = m_process->GetStopID();
217 }
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000218}
219
Jason Molenda5fe4d142016-07-17 21:27:32 +0000220//----------------------------------------------------------------------
Adrian Prantl05097242018-04-30 16:49:04 +0000221// Update the load addresses for all segments in MODULE using the updated INFO
222// that is passed in.
Jason Molenda5fe4d142016-07-17 21:27:32 +0000223//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000224bool DynamicLoaderDarwin::UpdateImageLoadAddress(Module *module,
225 ImageInfo &info) {
226 bool changed = false;
227 if (module) {
228 ObjectFile *image_object_file = module->GetObjectFile();
229 if (image_object_file) {
230 SectionList *section_list = image_object_file->GetSectionList();
231 if (section_list) {
232 std::vector<uint32_t> inaccessible_segment_indexes;
Adrian Prantl05097242018-04-30 16:49:04 +0000233 // We now know the slide amount, so go through all sections and update
234 // the load addresses with the correct values.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000235 const size_t num_segments = info.segments.size();
236 for (size_t i = 0; i < num_segments; ++i) {
Adrian Prantl05097242018-04-30 16:49:04 +0000237 // Only load a segment if it has protections. Things like __PAGEZERO
238 // don't have any protections, and they shouldn't be slid
Kate Stoneb9c1b512016-09-06 20:57:50 +0000239 SectionSP section_sp(
240 section_list->FindSectionByName(info.segments[i].name));
Jason Molenda5fe4d142016-07-17 21:27:32 +0000241
Kate Stoneb9c1b512016-09-06 20:57:50 +0000242 if (info.segments[i].maxprot == 0) {
243 inaccessible_segment_indexes.push_back(i);
244 } else {
245 const addr_t new_section_load_addr =
246 info.segments[i].vmaddr + info.slide;
247 static ConstString g_section_name_LINKEDIT("__LINKEDIT");
Jason Molenda5fe4d142016-07-17 21:27:32 +0000248
Kate Stoneb9c1b512016-09-06 20:57:50 +0000249 if (section_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +0000250 // __LINKEDIT sections from files in the shared cache can overlap
251 // so check to see what the segment name is and pass "false" so
252 // we don't warn of overlapping "Section" objects, and "true" for
253 // all other sections.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000254 const bool warn_multiple =
255 section_sp->GetName() != g_section_name_LINKEDIT;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000256
Kate Stoneb9c1b512016-09-06 20:57:50 +0000257 changed = m_process->GetTarget().SetSectionLoadAddress(
258 section_sp, new_section_load_addr, warn_multiple);
259 } else {
260 Host::SystemLog(
261 Host::eSystemLogWarning,
262 "warning: unable to find and load segment named '%s' at "
263 "0x%" PRIx64 " in '%s' in macosx dynamic loader plug-in.\n",
264 info.segments[i].name.AsCString("<invalid>"),
265 (uint64_t)new_section_load_addr,
266 image_object_file->GetFileSpec().GetPath().c_str());
Jason Molenda5fe4d142016-07-17 21:27:32 +0000267 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000268 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000269 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000270
Adrian Prantl05097242018-04-30 16:49:04 +0000271 // If the loaded the file (it changed) and we have segments that are
272 // not readable or writeable, add them to the invalid memory region
273 // cache for the process. This will typically only be the __PAGEZERO
274 // segment in the main executable. We might be able to apply this more
275 // generally to more sections that have no protections in the future,
276 // but for now we are going to just do __PAGEZERO.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000277 if (changed && !inaccessible_segment_indexes.empty()) {
278 for (uint32_t i = 0; i < inaccessible_segment_indexes.size(); ++i) {
279 const uint32_t seg_idx = inaccessible_segment_indexes[i];
280 SectionSP section_sp(
281 section_list->FindSectionByName(info.segments[seg_idx].name));
282
283 if (section_sp) {
284 static ConstString g_pagezero_section_name("__PAGEZERO");
285 if (g_pagezero_section_name == section_sp->GetName()) {
286 // __PAGEZERO never slides...
287 const lldb::addr_t vmaddr = info.segments[seg_idx].vmaddr;
288 const lldb::addr_t vmsize = info.segments[seg_idx].vmsize;
289 Process::LoadRange pagezero_range(vmaddr, vmsize);
290 m_process->AddInvalidMemoryRegion(pagezero_range);
291 }
292 }
293 }
294 }
295 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000296 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000297 }
298 // We might have an in memory image that was loaded as soon as it was created
299 if (info.load_stop_id == m_process->GetStopID())
300 changed = true;
301 else if (changed) {
302 // Update the stop ID when this library was updated
303 info.load_stop_id = m_process->GetStopID();
304 }
305 return changed;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000306}
307
308//----------------------------------------------------------------------
309// Unload the segments in MODULE using the INFO that is passed in.
310//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000311bool DynamicLoaderDarwin::UnloadModuleSections(Module *module,
312 ImageInfo &info) {
313 bool changed = false;
314 if (module) {
315 ObjectFile *image_object_file = module->GetObjectFile();
316 if (image_object_file) {
317 SectionList *section_list = image_object_file->GetSectionList();
318 if (section_list) {
319 const size_t num_segments = info.segments.size();
320 for (size_t i = 0; i < num_segments; ++i) {
321 SectionSP section_sp(
322 section_list->FindSectionByName(info.segments[i].name));
323 if (section_sp) {
324 const addr_t old_section_load_addr =
325 info.segments[i].vmaddr + info.slide;
326 if (m_process->GetTarget().SetSectionUnloaded(
327 section_sp, old_section_load_addr))
328 changed = true;
329 } else {
330 Host::SystemLog(Host::eSystemLogWarning,
331 "warning: unable to find and unload segment named "
332 "'%s' in '%s' in macosx dynamic loader plug-in.\n",
333 info.segments[i].name.AsCString("<invalid>"),
334 image_object_file->GetFileSpec().GetPath().c_str());
335 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000336 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000337 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000338 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000339 }
340 return changed;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000341}
342
Kate Stoneb9c1b512016-09-06 20:57:50 +0000343// Given a JSON dictionary (from debugserver, most likely) of binary images
Adrian Prantl05097242018-04-30 16:49:04 +0000344// loaded in the inferior process, add the images to the ImageInfo collection.
Jason Molenda5fe4d142016-07-17 21:27:32 +0000345
Kate Stoneb9c1b512016-09-06 20:57:50 +0000346bool DynamicLoaderDarwin::JSONImageInformationIntoImageInfo(
347 StructuredData::ObjectSP image_details,
348 ImageInfo::collection &image_infos) {
349 StructuredData::ObjectSP images_sp =
350 image_details->GetAsDictionary()->GetValueForKey("images");
351 if (images_sp.get() == nullptr)
352 return false;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000353
Kate Stoneb9c1b512016-09-06 20:57:50 +0000354 image_infos.resize(images_sp->GetAsArray()->GetSize());
Jason Molenda5fe4d142016-07-17 21:27:32 +0000355
Kate Stoneb9c1b512016-09-06 20:57:50 +0000356 for (size_t i = 0; i < image_infos.size(); i++) {
357 StructuredData::ObjectSP image_sp =
358 images_sp->GetAsArray()->GetItemAtIndex(i);
359 if (image_sp.get() == nullptr || image_sp->GetAsDictionary() == nullptr)
360 return false;
361 StructuredData::Dictionary *image = image_sp->GetAsDictionary();
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000362 // clang-format off
363 if (!image->HasKey("load_address") ||
364 !image->HasKey("pathname") ||
365 !image->HasKey("mod_date") ||
366 !image->HasKey("mach_header") ||
Kate Stoneb9c1b512016-09-06 20:57:50 +0000367 image->GetValueForKey("mach_header")->GetAsDictionary() == nullptr ||
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000368 !image->HasKey("segments") ||
Kate Stoneb9c1b512016-09-06 20:57:50 +0000369 image->GetValueForKey("segments")->GetAsArray() == nullptr ||
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000370 !image->HasKey("uuid")) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000371 return false;
372 }
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000373 // clang-format on
Kate Stoneb9c1b512016-09-06 20:57:50 +0000374 image_infos[i].address =
375 image->GetValueForKey("load_address")->GetAsInteger()->GetValue();
376 image_infos[i].mod_date =
377 image->GetValueForKey("mod_date")->GetAsInteger()->GetValue();
378 image_infos[i].file_spec.SetFile(
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000379 image->GetValueForKey("pathname")->GetAsString()->GetValue(),
Jonas Devlieghere937348c2018-06-13 22:08:14 +0000380 FileSpec::Style::native);
Jason Molenda5fe4d142016-07-17 21:27:32 +0000381
Kate Stoneb9c1b512016-09-06 20:57:50 +0000382 StructuredData::Dictionary *mh =
383 image->GetValueForKey("mach_header")->GetAsDictionary();
384 image_infos[i].header.magic =
385 mh->GetValueForKey("magic")->GetAsInteger()->GetValue();
386 image_infos[i].header.cputype =
387 mh->GetValueForKey("cputype")->GetAsInteger()->GetValue();
388 image_infos[i].header.cpusubtype =
389 mh->GetValueForKey("cpusubtype")->GetAsInteger()->GetValue();
390 image_infos[i].header.filetype =
391 mh->GetValueForKey("filetype")->GetAsInteger()->GetValue();
Jason Molenda5fe4d142016-07-17 21:27:32 +0000392
Kate Stoneb9c1b512016-09-06 20:57:50 +0000393 if (image->HasKey("min_version_os_name")) {
394 std::string os_name = image->GetValueForKey("min_version_os_name")
395 ->GetAsString()
396 ->GetValue();
397 if (os_name == "macosx")
398 image_infos[i].os_type = llvm::Triple::MacOSX;
399 else if (os_name == "ios" || os_name == "iphoneos")
400 image_infos[i].os_type = llvm::Triple::IOS;
401 else if (os_name == "tvos")
402 image_infos[i].os_type = llvm::Triple::TvOS;
403 else if (os_name == "watchos")
404 image_infos[i].os_type = llvm::Triple::WatchOS;
Jason Molenda32762fd2018-10-11 00:28:35 +0000405 // NEED_BRIDGEOS_TRIPLE else if (os_name == "bridgeos")
406 // NEED_BRIDGEOS_TRIPLE image_infos[i].os_type = llvm::Triple::BridgeOS;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000407 }
408 if (image->HasKey("min_version_os_sdk")) {
409 image_infos[i].min_version_os_sdk =
410 image->GetValueForKey("min_version_os_sdk")
411 ->GetAsString()
412 ->GetValue();
Jason Molenda5fe4d142016-07-17 21:27:32 +0000413 }
414
Kate Stoneb9c1b512016-09-06 20:57:50 +0000415 // Fields that aren't used by DynamicLoaderDarwin so debugserver doesn't
Adrian Prantl05097242018-04-30 16:49:04 +0000416 // currently send them in the reply.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000417
418 if (mh->HasKey("flags"))
419 image_infos[i].header.flags =
420 mh->GetValueForKey("flags")->GetAsInteger()->GetValue();
421 else
422 image_infos[i].header.flags = 0;
423
424 if (mh->HasKey("ncmds"))
425 image_infos[i].header.ncmds =
426 mh->GetValueForKey("ncmds")->GetAsInteger()->GetValue();
427 else
428 image_infos[i].header.ncmds = 0;
429
430 if (mh->HasKey("sizeofcmds"))
431 image_infos[i].header.sizeofcmds =
432 mh->GetValueForKey("sizeofcmds")->GetAsInteger()->GetValue();
433 else
434 image_infos[i].header.sizeofcmds = 0;
435
436 StructuredData::Array *segments =
437 image->GetValueForKey("segments")->GetAsArray();
438 uint32_t segcount = segments->GetSize();
439 for (size_t j = 0; j < segcount; j++) {
440 Segment segment;
441 StructuredData::Dictionary *seg =
442 segments->GetItemAtIndex(j)->GetAsDictionary();
Zachary Turner28333212017-05-12 05:49:54 +0000443 segment.name =
444 ConstString(seg->GetValueForKey("name")->GetAsString()->GetValue());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000445 segment.vmaddr =
446 seg->GetValueForKey("vmaddr")->GetAsInteger()->GetValue();
447 segment.vmsize =
448 seg->GetValueForKey("vmsize")->GetAsInteger()->GetValue();
449 segment.fileoff =
450 seg->GetValueForKey("fileoff")->GetAsInteger()->GetValue();
451 segment.filesize =
452 seg->GetValueForKey("filesize")->GetAsInteger()->GetValue();
453 segment.maxprot =
454 seg->GetValueForKey("maxprot")->GetAsInteger()->GetValue();
455
456 // Fields that aren't used by DynamicLoaderDarwin so debugserver doesn't
Adrian Prantl05097242018-04-30 16:49:04 +0000457 // currently send them in the reply.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000458
459 if (seg->HasKey("initprot"))
460 segment.initprot =
461 seg->GetValueForKey("initprot")->GetAsInteger()->GetValue();
462 else
463 segment.initprot = 0;
464
465 if (seg->HasKey("flags"))
466 segment.flags =
467 seg->GetValueForKey("flags")->GetAsInteger()->GetValue();
468 else
469 segment.flags = 0;
470
471 if (seg->HasKey("nsects"))
472 segment.nsects =
473 seg->GetValueForKey("nsects")->GetAsInteger()->GetValue();
474 else
475 segment.nsects = 0;
476
477 image_infos[i].segments.push_back(segment);
478 }
479
Zachary Turner28333212017-05-12 05:49:54 +0000480 image_infos[i].uuid.SetFromStringRef(
481 image->GetValueForKey("uuid")->GetAsString()->GetValue());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000482
Adrian Prantl05097242018-04-30 16:49:04 +0000483 // All sections listed in the dyld image info structure will all either be
484 // fixed up already, or they will all be off by a single slide amount that
485 // is determined by finding the first segment that is at file offset zero
486 // which also has bytes (a file size that is greater than zero) in the
487 // object file.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000488
489 // Determine the slide amount (if any)
490 const size_t num_sections = image_infos[i].segments.size();
491 for (size_t k = 0; k < num_sections; ++k) {
Adrian Prantl05097242018-04-30 16:49:04 +0000492 // Iterate through the object file sections to find the first section
493 // that starts of file offset zero and that has bytes in the file...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000494 if ((image_infos[i].segments[k].fileoff == 0 &&
495 image_infos[i].segments[k].filesize > 0) ||
496 (image_infos[i].segments[k].name == ConstString("__TEXT"))) {
497 image_infos[i].slide =
498 image_infos[i].address - image_infos[i].segments[k].vmaddr;
Adrian Prantl05097242018-04-30 16:49:04 +0000499 // We have found the slide amount, so we can exit this for loop.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000500 break;
501 }
502 }
503 }
504
505 return true;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000506}
507
Kate Stoneb9c1b512016-09-06 20:57:50 +0000508void DynamicLoaderDarwin::UpdateSpecialBinariesFromNewImageInfos(
509 ImageInfo::collection &image_infos) {
510 uint32_t exe_idx = UINT32_MAX;
511 uint32_t dyld_idx = UINT32_MAX;
512 Target &target = m_process->GetTarget();
513 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
514 ConstString g_dyld_sim_filename("dyld_sim");
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000515
Kate Stoneb9c1b512016-09-06 20:57:50 +0000516 ArchSpec target_arch = target.GetArchitecture();
517 const size_t image_infos_size = image_infos.size();
518 for (size_t i = 0; i < image_infos_size; i++) {
519 if (image_infos[i].header.filetype == llvm::MachO::MH_DYLINKER) {
Jason Molenda32762fd2018-10-11 00:28:35 +0000520 // In a "simulator" process (an x86 process that is
521 // ios/tvos/watchos/bridgeos) we will have two dyld modules --
522 // a "dyld" that we want to keep track of, and a "dyld_sim" which
523 // we don't need to keep track of here. If the target is an x86
524 // system and the OS of the dyld binary is ios/tvos/watchos/bridgeos,
525 // then we are looking at dyld_sym.
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000526
Adrian Prantl05097242018-04-30 16:49:04 +0000527 // debugserver has only recently (late 2016) started sending up the os
528 // type for each binary it sees -- so if we don't have an os type, use a
529 // filename check as our next best guess.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000530 if (image_infos[i].os_type == llvm::Triple::OSType::UnknownOS) {
531 if (image_infos[i].file_spec.GetFilename() != g_dyld_sim_filename) {
532 dyld_idx = i;
533 }
534 } else if (target_arch.GetTriple().getArch() == llvm::Triple::x86 ||
535 target_arch.GetTriple().getArch() == llvm::Triple::x86_64) {
536 if (image_infos[i].os_type != llvm::Triple::OSType::IOS &&
537 image_infos[i].os_type != llvm::Triple::TvOS &&
538 image_infos[i].os_type != llvm::Triple::WatchOS) {
Jason Molenda32762fd2018-10-11 00:28:35 +0000539 // NEED_BRIDGEOS_TRIPLE image_infos[i].os_type != llvm::Triple::BridgeOS) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000540 dyld_idx = i;
541 }
542 }
Jason Molenda777fcec2017-01-21 01:17:36 +0000543 else {
Adrian Prantl05097242018-04-30 16:49:04 +0000544 // catch-all for any other environment -- trust that dyld is actually
545 // dyld
Jason Molenda777fcec2017-01-21 01:17:36 +0000546 dyld_idx = i;
547 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000548 } else if (image_infos[i].header.filetype == llvm::MachO::MH_EXECUTE) {
549 exe_idx = i;
550 }
551 }
552
553 if (exe_idx != UINT32_MAX) {
554 const bool can_create = true;
555 ModuleSP exe_module_sp(
556 FindTargetModuleForImageInfo(image_infos[exe_idx], can_create, NULL));
557 if (exe_module_sp) {
558 if (log)
559 log->Printf("Found executable module: %s",
560 exe_module_sp->GetFileSpec().GetPath().c_str());
561 target.GetImages().AppendIfNeeded(exe_module_sp);
562 UpdateImageLoadAddress(exe_module_sp.get(), image_infos[exe_idx]);
563 if (exe_module_sp.get() != target.GetExecutableModulePointer()) {
Jonas Devliegheref9a07e92018-09-20 09:09:05 +0000564 target.SetExecutableModule(exe_module_sp, eLoadDependentsNo);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000565 }
566 }
567 }
568
569 if (dyld_idx != UINT32_MAX) {
570 const bool can_create = true;
571 ModuleSP dyld_sp =
572 FindTargetModuleForImageInfo(image_infos[dyld_idx], can_create, NULL);
573 if (dyld_sp.get()) {
574 if (log)
575 log->Printf("Found dyld module: %s",
576 dyld_sp->GetFileSpec().GetPath().c_str());
577 target.GetImages().AppendIfNeeded(dyld_sp);
578 UpdateImageLoadAddress(dyld_sp.get(), image_infos[dyld_idx]);
579 SetDYLDModule(dyld_sp);
580 }
581 }
582}
583
584void DynamicLoaderDarwin::UpdateDYLDImageInfoFromNewImageInfo(
585 ImageInfo &image_info) {
586 if (image_info.header.filetype == llvm::MachO::MH_DYLINKER) {
587 const bool can_create = true;
588 ModuleSP dyld_sp =
589 FindTargetModuleForImageInfo(image_info, can_create, NULL);
590 if (dyld_sp.get()) {
591 Target &target = m_process->GetTarget();
592 target.GetImages().AppendIfNeeded(dyld_sp);
593 UpdateImageLoadAddress(dyld_sp.get(), image_info);
594 SetDYLDModule(dyld_sp);
595 }
596 }
597}
598
599void DynamicLoaderDarwin::SetDYLDModule(lldb::ModuleSP &dyld_module_sp) {
600 m_dyld_module_wp = dyld_module_sp;
601}
602
603ModuleSP DynamicLoaderDarwin::GetDYLDModule() {
604 ModuleSP dyld_sp(m_dyld_module_wp.lock());
605 return dyld_sp;
606}
607
608bool DynamicLoaderDarwin::AddModulesUsingImageInfos(
609 ImageInfo::collection &image_infos) {
610 std::lock_guard<std::recursive_mutex> guard(m_mutex);
611 // Now add these images to the main list.
612 ModuleList loaded_module_list;
613 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
614 Target &target = m_process->GetTarget();
615 ModuleList &target_images = target.GetImages();
616
617 for (uint32_t idx = 0; idx < image_infos.size(); ++idx) {
618 if (log) {
619 log->Printf("Adding new image at address=0x%16.16" PRIx64 ".",
620 image_infos[idx].address);
621 image_infos[idx].PutToLog(log);
622 }
623
624 m_dyld_image_infos.push_back(image_infos[idx]);
625
626 ModuleSP image_module_sp(
627 FindTargetModuleForImageInfo(image_infos[idx], true, NULL));
628
629 if (image_module_sp) {
630 ObjectFile *objfile = image_module_sp->GetObjectFile();
631 if (objfile) {
632 SectionList *sections = objfile->GetSectionList();
633 if (sections) {
634 ConstString commpage_dbstr("__commpage");
635 Section *commpage_section =
636 sections->FindSectionByName(commpage_dbstr).get();
637 if (commpage_section) {
638 ModuleSpec module_spec(objfile->GetFileSpec(),
639 image_infos[idx].GetArchitecture());
640 module_spec.GetObjectName() = commpage_dbstr;
641 ModuleSP commpage_image_module_sp(
642 target_images.FindFirstModule(module_spec));
643 if (!commpage_image_module_sp) {
644 module_spec.SetObjectOffset(objfile->GetFileOffset() +
645 commpage_section->GetFileOffset());
646 module_spec.SetObjectSize(objfile->GetByteSize());
647 commpage_image_module_sp = target.GetSharedModule(module_spec);
648 if (!commpage_image_module_sp ||
649 commpage_image_module_sp->GetObjectFile() == NULL) {
650 commpage_image_module_sp = m_process->ReadModuleFromMemory(
651 image_infos[idx].file_spec, image_infos[idx].address);
652 // Always load a memory image right away in the target in case
653 // we end up trying to read the symbol table from memory... The
654 // __LINKEDIT will need to be mapped so we can figure out where
655 // the symbol table bits are...
656 bool changed = false;
657 UpdateImageLoadAddress(commpage_image_module_sp.get(),
658 image_infos[idx]);
659 target.GetImages().Append(commpage_image_module_sp);
660 if (changed) {
661 image_infos[idx].load_stop_id = m_process->GetStopID();
662 loaded_module_list.AppendIfNeeded(commpage_image_module_sp);
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000663 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000664 }
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000665 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000666 }
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000667 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000668 }
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000669
Adrian Prantl05097242018-04-30 16:49:04 +0000670 // UpdateImageLoadAddress will return true if any segments change load
671 // address. We need to check this so we don't mention that all loaded
672 // shared libraries are newly loaded each time we hit out dyld breakpoint
673 // since dyld will list all shared libraries each time.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000674 if (UpdateImageLoadAddress(image_module_sp.get(), image_infos[idx])) {
675 target_images.AppendIfNeeded(image_module_sp);
676 loaded_module_list.AppendIfNeeded(image_module_sp);
677 }
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000678 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000679 }
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000680
Kate Stoneb9c1b512016-09-06 20:57:50 +0000681 if (loaded_module_list.GetSize() > 0) {
682 if (log)
683 loaded_module_list.LogUUIDAndPaths(log,
684 "DynamicLoaderDarwin::ModulesDidLoad");
685 m_process->GetTarget().ModulesDidLoad(loaded_module_list);
686 }
687 return true;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000688}
689
Jason Molenda5fe4d142016-07-17 21:27:32 +0000690//----------------------------------------------------------------------
691// On Mac OS X libobjc (the Objective-C runtime) has several critical dispatch
Adrian Prantl05097242018-04-30 16:49:04 +0000692// functions written in hand-written assembly, and also have hand-written
693// unwind information in the eh_frame section. Normally we prefer analyzing
694// the assembly instructions of a currently executing frame to unwind from that
695// frame -- but on hand-written functions this profiling can fail. We should
696// use the eh_frame instructions for these functions all the time.
Jason Molenda5fe4d142016-07-17 21:27:32 +0000697//
698// As an aside, it would be better if the eh_frame entries had a flag (or were
699// extensible so they could have an Apple-specific flag) which indicates that
700// the instructions are asynchronous -- accurate at every instruction, instead
701// of our normal default assumption that they are not.
702//----------------------------------------------------------------------
703
Kate Stoneb9c1b512016-09-06 20:57:50 +0000704bool DynamicLoaderDarwin::AlwaysRelyOnEHUnwindInfo(SymbolContext &sym_ctx) {
705 ModuleSP module_sp;
706 if (sym_ctx.symbol) {
707 module_sp = sym_ctx.symbol->GetAddressRef().GetModule();
708 }
709 if (module_sp.get() == NULL && sym_ctx.function) {
710 module_sp =
711 sym_ctx.function->GetAddressRange().GetBaseAddress().GetModule();
712 }
713 if (module_sp.get() == NULL)
Jason Molenda5fe4d142016-07-17 21:27:32 +0000714 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000715
716 ObjCLanguageRuntime *objc_runtime = m_process->GetObjCLanguageRuntime();
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000717 return objc_runtime != NULL && objc_runtime->IsModuleObjCLibrary(module_sp);
Jason Molenda5fe4d142016-07-17 21:27:32 +0000718}
719
Jason Molenda5fe4d142016-07-17 21:27:32 +0000720//----------------------------------------------------------------------
721// Dump a Segment to the file handle provided.
722//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000723void DynamicLoaderDarwin::Segment::PutToLog(Log *log,
724 lldb::addr_t slide) const {
725 if (log) {
726 if (slide == 0)
727 log->Printf("\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ")",
728 name.AsCString(""), vmaddr + slide, vmaddr + slide + vmsize);
729 else
730 log->Printf("\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64
731 ") slide = 0x%" PRIx64,
732 name.AsCString(""), vmaddr + slide, vmaddr + slide + vmsize,
733 slide);
734 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000735}
736
737const DynamicLoaderDarwin::Segment *
Kate Stoneb9c1b512016-09-06 20:57:50 +0000738DynamicLoaderDarwin::ImageInfo::FindSegment(const ConstString &name) const {
739 const size_t num_segments = segments.size();
740 for (size_t i = 0; i < num_segments; ++i) {
741 if (segments[i].name == name)
742 return &segments[i];
743 }
744 return NULL;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000745}
746
Jason Molenda5fe4d142016-07-17 21:27:32 +0000747//----------------------------------------------------------------------
748// Dump an image info structure to the file handle provided.
749//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000750void DynamicLoaderDarwin::ImageInfo::PutToLog(Log *log) const {
Pavel Labathfbb14282018-06-20 20:13:04 +0000751 if (!log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000752 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000753 if (address == LLDB_INVALID_ADDRESS) {
Pavel Labathfbb14282018-06-20 20:13:04 +0000754 LLDB_LOG(log, "modtime={0:x+8} uuid={1} path='{2}' (UNLOADED)", mod_date,
755 uuid.GetAsString(), file_spec.GetPath());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000756 } else {
Pavel Labathfbb14282018-06-20 20:13:04 +0000757 LLDB_LOG(log, "address={0:x+16} modtime={1:x+8} uuid={2} path='{3}'",
758 address, mod_date, uuid.GetAsString(), file_spec.GetPath());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000759 for (uint32_t i = 0; i < segments.size(); ++i)
760 segments[i].PutToLog(log, slide);
761 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000762}
763
Kate Stoneb9c1b512016-09-06 20:57:50 +0000764void DynamicLoaderDarwin::PrivateInitialize(Process *process) {
765 DEBUG_PRINTF("DynamicLoaderDarwin::%s() process state = %s\n", __FUNCTION__,
766 StateAsCString(m_process->GetState()));
767 Clear(true);
768 m_process = process;
769 m_process->GetTarget().ClearAllLoadedSections();
Jason Molenda5fe4d142016-07-17 21:27:32 +0000770}
771
772//----------------------------------------------------------------------
773// Member function that gets called when the process state changes.
774//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000775void DynamicLoaderDarwin::PrivateProcessStateChanged(Process *process,
776 StateType state) {
777 DEBUG_PRINTF("DynamicLoaderDarwin::%s(%s)\n", __FUNCTION__,
778 StateAsCString(state));
779 switch (state) {
780 case eStateConnected:
781 case eStateAttaching:
782 case eStateLaunching:
783 case eStateInvalid:
784 case eStateUnloaded:
785 case eStateExited:
786 case eStateDetached:
787 Clear(false);
788 break;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000789
Kate Stoneb9c1b512016-09-06 20:57:50 +0000790 case eStateStopped:
Adrian Prantl05097242018-04-30 16:49:04 +0000791 // Keep trying find dyld and set our notification breakpoint each time we
792 // stop until we succeed
Kate Stoneb9c1b512016-09-06 20:57:50 +0000793 if (!DidSetNotificationBreakpoint() && m_process->IsAlive()) {
794 if (NeedToDoInitialImageFetch())
795 DoInitialImageFetch();
Jason Molenda5fe4d142016-07-17 21:27:32 +0000796
Kate Stoneb9c1b512016-09-06 20:57:50 +0000797 SetNotificationBreakpoint();
Jason Molenda5fe4d142016-07-17 21:27:32 +0000798 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000799 break;
800
801 case eStateRunning:
802 case eStateStepping:
803 case eStateCrashed:
804 case eStateSuspended:
805 break;
806 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000807}
808
809ThreadPlanSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000810DynamicLoaderDarwin::GetStepThroughTrampolinePlan(Thread &thread,
811 bool stop_others) {
812 ThreadPlanSP thread_plan_sp;
813 StackFrame *current_frame = thread.GetStackFrameAtIndex(0).get();
814 const SymbolContext &current_context =
815 current_frame->GetSymbolContext(eSymbolContextSymbol);
816 Symbol *current_symbol = current_context.symbol;
817 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
818 TargetSP target_sp(thread.CalculateTarget());
Jason Molenda5fe4d142016-07-17 21:27:32 +0000819
Kate Stoneb9c1b512016-09-06 20:57:50 +0000820 if (current_symbol != NULL) {
821 std::vector<Address> addresses;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000822
Kate Stoneb9c1b512016-09-06 20:57:50 +0000823 if (current_symbol->IsTrampoline()) {
824 const ConstString &trampoline_name = current_symbol->GetMangled().GetName(
825 current_symbol->GetLanguage(), Mangled::ePreferMangled);
Jason Molenda5fe4d142016-07-17 21:27:32 +0000826
Kate Stoneb9c1b512016-09-06 20:57:50 +0000827 if (trampoline_name) {
828 const ModuleList &images = target_sp->GetImages();
829
830 SymbolContextList code_symbols;
831 images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeCode,
832 code_symbols);
833 size_t num_code_symbols = code_symbols.GetSize();
834
835 if (num_code_symbols > 0) {
836 for (uint32_t i = 0; i < num_code_symbols; i++) {
837 SymbolContext context;
838 AddressRange addr_range;
839 if (code_symbols.GetContextAtIndex(i, context)) {
840 context.GetAddressRange(eSymbolContextEverything, 0, false,
841 addr_range);
842 addresses.push_back(addr_range.GetBaseAddress());
843 if (log) {
844 addr_t load_addr =
845 addr_range.GetBaseAddress().GetLoadAddress(target_sp.get());
846
847 log->Printf("Found a trampoline target symbol at 0x%" PRIx64
848 ".",
849 load_addr);
850 }
851 }
852 }
853 }
854
855 SymbolContextList reexported_symbols;
856 images.FindSymbolsWithNameAndType(
857 trampoline_name, eSymbolTypeReExported, reexported_symbols);
858 size_t num_reexported_symbols = reexported_symbols.GetSize();
859 if (num_reexported_symbols > 0) {
860 for (uint32_t i = 0; i < num_reexported_symbols; i++) {
861 SymbolContext context;
862 if (reexported_symbols.GetContextAtIndex(i, context)) {
863 if (context.symbol) {
864 Symbol *actual_symbol =
865 context.symbol->ResolveReExportedSymbol(*target_sp.get());
866 if (actual_symbol) {
867 const Address actual_symbol_addr =
868 actual_symbol->GetAddress();
869 if (actual_symbol_addr.IsValid()) {
870 addresses.push_back(actual_symbol_addr);
871 if (log) {
872 lldb::addr_t load_addr =
873 actual_symbol_addr.GetLoadAddress(target_sp.get());
874 log->Printf(
875 "Found a re-exported symbol: %s at 0x%" PRIx64 ".",
876 actual_symbol->GetName().GetCString(), load_addr);
Jason Molenda5fe4d142016-07-17 21:27:32 +0000877 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000878 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000879 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000880 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000881 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000882 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000883 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000884
885 SymbolContextList indirect_symbols;
886 images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeResolver,
887 indirect_symbols);
888 size_t num_indirect_symbols = indirect_symbols.GetSize();
889 if (num_indirect_symbols > 0) {
890 for (uint32_t i = 0; i < num_indirect_symbols; i++) {
891 SymbolContext context;
892 AddressRange addr_range;
893 if (indirect_symbols.GetContextAtIndex(i, context)) {
894 context.GetAddressRange(eSymbolContextEverything, 0, false,
895 addr_range);
896 addresses.push_back(addr_range.GetBaseAddress());
897 if (log) {
898 addr_t load_addr =
899 addr_range.GetBaseAddress().GetLoadAddress(target_sp.get());
900
901 log->Printf("Found an indirect target symbol at 0x%" PRIx64 ".",
902 load_addr);
903 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000904 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000905 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000906 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000907 }
908 } else if (current_symbol->GetType() == eSymbolTypeReExported) {
909 // I am not sure we could ever end up stopped AT a re-exported symbol.
910 // But just in case:
911
912 const Symbol *actual_symbol =
913 current_symbol->ResolveReExportedSymbol(*(target_sp.get()));
914 if (actual_symbol) {
915 Address target_addr(actual_symbol->GetAddress());
916 if (target_addr.IsValid()) {
917 if (log)
918 log->Printf(
919 "Found a re-exported symbol: %s pointing to: %s at 0x%" PRIx64
920 ".",
921 current_symbol->GetName().GetCString(),
922 actual_symbol->GetName().GetCString(),
923 target_addr.GetLoadAddress(target_sp.get()));
924 addresses.push_back(target_addr.GetLoadAddress(target_sp.get()));
Jason Molenda5fe4d142016-07-17 21:27:32 +0000925 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000926 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000927 }
928
Kate Stoneb9c1b512016-09-06 20:57:50 +0000929 if (addresses.size() > 0) {
Adrian Prantl05097242018-04-30 16:49:04 +0000930 // First check whether any of the addresses point to Indirect symbols,
931 // and if they do, resolve them:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000932 std::vector<lldb::addr_t> load_addrs;
933 for (Address address : addresses) {
934 Symbol *symbol = address.CalculateSymbolContextSymbol();
935 if (symbol && symbol->IsIndirect()) {
Zachary Turner97206d52017-05-12 04:51:55 +0000936 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000937 Address symbol_address = symbol->GetAddress();
938 addr_t resolved_addr = thread.GetProcess()->ResolveIndirectFunction(
939 &symbol_address, error);
940 if (error.Success()) {
941 load_addrs.push_back(resolved_addr);
942 if (log)
943 log->Printf("ResolveIndirectFunction found resolved target for "
944 "%s at 0x%" PRIx64 ".",
945 symbol->GetName().GetCString(), resolved_addr);
946 }
947 } else {
948 load_addrs.push_back(address.GetLoadAddress(target_sp.get()));
Jason Molenda5fe4d142016-07-17 21:27:32 +0000949 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000950 }
951 thread_plan_sp.reset(
952 new ThreadPlanRunToAddress(thread, load_addrs, stop_others));
Jason Molenda5fe4d142016-07-17 21:27:32 +0000953 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000954 } else {
955 if (log)
956 log->Printf("Could not find symbol for step through.");
957 }
958
959 return thread_plan_sp;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000960}
961
Kate Stoneb9c1b512016-09-06 20:57:50 +0000962size_t DynamicLoaderDarwin::FindEquivalentSymbols(
963 lldb_private::Symbol *original_symbol, lldb_private::ModuleList &images,
964 lldb_private::SymbolContextList &equivalent_symbols) {
965 const ConstString &trampoline_name = original_symbol->GetMangled().GetName(
966 original_symbol->GetLanguage(), Mangled::ePreferMangled);
967 if (!trampoline_name)
968 return 0;
969
970 size_t initial_size = equivalent_symbols.GetSize();
971
972 static const char *resolver_name_regex = "(_gc|_non_gc|\\$[A-Za-z0-9\\$]+)$";
973 std::string equivalent_regex_buf("^");
974 equivalent_regex_buf.append(trampoline_name.GetCString());
975 equivalent_regex_buf.append(resolver_name_regex);
976
Zachary Turner95eae422016-09-21 16:01:28 +0000977 RegularExpression equivalent_name_regex(equivalent_regex_buf);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000978 const bool append = true;
979 images.FindSymbolsMatchingRegExAndType(equivalent_name_regex, eSymbolTypeCode,
980 equivalent_symbols, append);
981
982 return equivalent_symbols.GetSize() - initial_size;
983}
984
985lldb::ModuleSP DynamicLoaderDarwin::GetPThreadLibraryModule() {
986 ModuleSP module_sp = m_libpthread_module_wp.lock();
987 if (!module_sp) {
988 SymbolContextList sc_list;
989 ModuleSpec module_spec;
990 module_spec.GetFileSpec().GetFilename().SetCString(
991 "libsystem_pthread.dylib");
992 ModuleList module_list;
993 if (m_process->GetTarget().GetImages().FindModules(module_spec,
994 module_list)) {
995 if (module_list.GetSize() == 1) {
996 module_sp = module_list.GetModuleAtIndex(0);
Jason Molenda5fe4d142016-07-17 21:27:32 +0000997 if (module_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000998 m_libpthread_module_wp = module_sp;
999 }
Jason Molenda5fe4d142016-07-17 21:27:32 +00001000 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001001 }
1002 return module_sp;
1003}
1004
1005Address DynamicLoaderDarwin::GetPthreadSetSpecificAddress() {
1006 if (!m_pthread_getspecific_addr.IsValid()) {
1007 ModuleSP module_sp = GetPThreadLibraryModule();
1008 if (module_sp) {
1009 lldb_private::SymbolContextList sc_list;
1010 module_sp->FindSymbolsWithNameAndType(ConstString("pthread_getspecific"),
1011 eSymbolTypeCode, sc_list);
1012 SymbolContext sc;
1013 if (sc_list.GetContextAtIndex(0, sc)) {
1014 if (sc.symbol)
1015 m_pthread_getspecific_addr = sc.symbol->GetAddress();
1016 }
1017 }
1018 }
1019 return m_pthread_getspecific_addr;
Jason Molenda5fe4d142016-07-17 21:27:32 +00001020}
1021
1022lldb::addr_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001023DynamicLoaderDarwin::GetThreadLocalData(const lldb::ModuleSP module_sp,
1024 const lldb::ThreadSP thread_sp,
1025 lldb::addr_t tls_file_addr) {
1026 if (!thread_sp || !module_sp)
Jason Molenda5fe4d142016-07-17 21:27:32 +00001027 return LLDB_INVALID_ADDRESS;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001028
1029 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1030
1031 const uint32_t addr_size = m_process->GetAddressByteSize();
1032 uint8_t buf[sizeof(lldb::addr_t) * 3];
1033
1034 lldb_private::Address tls_addr;
1035 if (module_sp->ResolveFileAddress(tls_file_addr, tls_addr)) {
Zachary Turner97206d52017-05-12 04:51:55 +00001036 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001037 const size_t tsl_data_size = addr_size * 3;
1038 Target &target = m_process->GetTarget();
1039 if (target.ReadMemory(tls_addr, false, buf, tsl_data_size, error) ==
1040 tsl_data_size) {
1041 const ByteOrder byte_order = m_process->GetByteOrder();
1042 DataExtractor data(buf, sizeof(buf), byte_order, addr_size);
1043 lldb::offset_t offset = addr_size; // Skip the first pointer
1044 const lldb::addr_t pthread_key = data.GetAddress(&offset);
1045 const lldb::addr_t tls_offset = data.GetAddress(&offset);
1046 if (pthread_key != 0) {
Adrian Prantl05097242018-04-30 16:49:04 +00001047 // First check to see if we have already figured out the location of
1048 // TLS data for the pthread_key on a specific thread yet. If we have we
1049 // can re-use it since its location will not change unless the process
1050 // execs.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001051 const tid_t tid = thread_sp->GetID();
1052 auto tid_pos = m_tid_to_tls_map.find(tid);
1053 if (tid_pos != m_tid_to_tls_map.end()) {
1054 auto tls_pos = tid_pos->second.find(pthread_key);
1055 if (tls_pos != tid_pos->second.end()) {
1056 return tls_pos->second + tls_offset;
1057 }
1058 }
1059 StackFrameSP frame_sp = thread_sp->GetStackFrameAtIndex(0);
1060 if (frame_sp) {
1061 ClangASTContext *clang_ast_context =
1062 target.GetScratchClangASTContext();
1063
1064 if (!clang_ast_context)
1065 return LLDB_INVALID_ADDRESS;
1066
1067 CompilerType clang_void_ptr_type =
1068 clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
1069 Address pthread_getspecific_addr = GetPthreadSetSpecificAddress();
1070 if (pthread_getspecific_addr.IsValid()) {
1071 EvaluateExpressionOptions options;
1072
1073 lldb::ThreadPlanSP thread_plan_sp(new ThreadPlanCallFunction(
1074 *thread_sp, pthread_getspecific_addr, clang_void_ptr_type,
1075 llvm::ArrayRef<lldb::addr_t>(pthread_key), options));
1076
1077 DiagnosticManager execution_errors;
1078 ExecutionContext exe_ctx(thread_sp);
1079 lldb::ExpressionResults results = m_process->RunThreadPlan(
1080 exe_ctx, thread_plan_sp, options, execution_errors);
1081
1082 if (results == lldb::eExpressionCompleted) {
1083 lldb::ValueObjectSP result_valobj_sp =
1084 thread_plan_sp->GetReturnValueObject();
1085 if (result_valobj_sp) {
1086 const lldb::addr_t pthread_key_data =
1087 result_valobj_sp->GetValueAsUnsigned(0);
1088 if (pthread_key_data) {
1089 m_tid_to_tls_map[tid].insert(
1090 std::make_pair(pthread_key, pthread_key_data));
1091 return pthread_key_data + tls_offset;
1092 }
1093 }
1094 }
1095 }
1096 }
1097 }
1098 }
1099 }
1100 return LLDB_INVALID_ADDRESS;
Jason Molenda5fe4d142016-07-17 21:27:32 +00001101}
1102
Kate Stoneb9c1b512016-09-06 20:57:50 +00001103bool DynamicLoaderDarwin::UseDYLDSPI(Process *process) {
1104 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001105 bool use_new_spi_interface = false;
Jason Molenda9ab5dc22016-07-21 08:30:55 +00001106
Pavel Labath2272c482018-06-18 15:02:23 +00001107 llvm::VersionTuple version = process->GetHostOSVersion();
1108 if (!version.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001109 const llvm::Triple::OSType os_type =
1110 process->GetTarget().GetArchitecture().GetTriple().getOS();
Jason Molenda9ab5dc22016-07-21 08:30:55 +00001111
Kate Stoneb9c1b512016-09-06 20:57:50 +00001112 // macOS 10.12 and newer
1113 if (os_type == llvm::Triple::MacOSX &&
Pavel Labath2272c482018-06-18 15:02:23 +00001114 version >= llvm::VersionTuple(10, 12))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001115 use_new_spi_interface = true;
Jason Molenda9ab5dc22016-07-21 08:30:55 +00001116
Kate Stoneb9c1b512016-09-06 20:57:50 +00001117 // iOS 10 and newer
Pavel Labath2272c482018-06-18 15:02:23 +00001118 if (os_type == llvm::Triple::IOS && version >= llvm::VersionTuple(10))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001119 use_new_spi_interface = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001120
1121 // tvOS 10 and newer
Pavel Labath2272c482018-06-18 15:02:23 +00001122 if (os_type == llvm::Triple::TvOS && version >= llvm::VersionTuple(10))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001123 use_new_spi_interface = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001124
1125 // watchOS 3 and newer
Pavel Labath2272c482018-06-18 15:02:23 +00001126 if (os_type == llvm::Triple::WatchOS && version >= llvm::VersionTuple(3))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001127 use_new_spi_interface = true;
Jason Molenda32762fd2018-10-11 00:28:35 +00001128
1129 // NEED_BRIDGEOS_TRIPLE // Any BridgeOS
1130 // NEED_BRIDGEOS_TRIPLE if (os_type == llvm::Triple::BridgeOS)
1131 // NEED_BRIDGEOS_TRIPLE use_new_spi_interface = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001132 }
1133
Kate Stoneb9c1b512016-09-06 20:57:50 +00001134 if (log) {
1135 if (use_new_spi_interface)
1136 log->Printf(
1137 "DynamicLoaderDarwin::UseDYLDSPI: Use new DynamicLoader plugin");
1138 else
1139 log->Printf(
1140 "DynamicLoaderDarwin::UseDYLDSPI: Use old DynamicLoader plugin");
1141 }
1142 return use_new_spi_interface;
Jason Molenda9ab5dc22016-07-21 08:30:55 +00001143}