blob: e7c07d29ba9d79e8292c712b5b25b06d21969608 [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"
13#include "lldb/Core/DataBuffer.h"
14#include "lldb/Core/DataBufferHeap.h"
15#include "lldb/Core/Debugger.h"
16#include "lldb/Core/Log.h"
17#include "lldb/Core/Module.h"
18#include "lldb/Core/ModuleSpec.h"
19#include "lldb/Core/PluginManager.h"
20#include "lldb/Core/Section.h"
21#include "lldb/Core/State.h"
22#include "lldb/Expression/DiagnosticManager.h"
Pavel Labath1408bf72016-11-01 16:11:14 +000023#include "lldb/Host/FileSystem.h"
Jason Molenda5fe4d142016-07-17 21:27:32 +000024#include "lldb/Symbol/ClangASTContext.h"
25#include "lldb/Symbol/Function.h"
26#include "lldb/Symbol/ObjectFile.h"
27#include "lldb/Target/ABI.h"
28#include "lldb/Target/ObjCLanguageRuntime.h"
29#include "lldb/Target/RegisterContext.h"
30#include "lldb/Target/StackFrame.h"
31#include "lldb/Target/Target.h"
32#include "lldb/Target/Thread.h"
33#include "lldb/Target/ThreadPlanCallFunction.h"
34#include "lldb/Target/ThreadPlanRunToAddress.h"
35
Jason Molenda5fe4d142016-07-17 21:27:32 +000036//#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN
37#ifdef ENABLE_DEBUG_PRINTF
38#include <stdio.h>
Kate Stoneb9c1b512016-09-06 20:57:50 +000039#define DEBUG_PRINTF(fmt, ...) printf(fmt, ##__VA_ARGS__)
Jason Molenda5fe4d142016-07-17 21:27:32 +000040#else
41#define DEBUG_PRINTF(fmt, ...)
42#endif
43
44#ifndef __APPLE__
45#include "Utility/UuidCompatibility.h"
46#else
47#include <uuid/uuid.h>
48#endif
49
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()) {
115 // No UUID, we must rely upon the cached module modification
116 // time and the modification time of the file on disk
117 if (module_sp->GetModificationTime() !=
Pavel Labath1408bf72016-11-01 16:11:14 +0000118 FileSystem::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
201 // libraries
202 // being re-loaded...
203 if (module_sp.get() != nullptr && module_sp.get() != dyld_sp.get()) {
204 UnloadSections(module_sp);
205 unloaded_modules_list.Append(module_sp);
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000206 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000207 }
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000208
Kate Stoneb9c1b512016-09-06 20:57:50 +0000209 if (unloaded_modules_list.GetSize() != 0) {
210 if (log) {
211 log->PutCString("Unloaded:");
212 unloaded_modules_list.LogUUIDAndPaths(
213 log, "DynamicLoaderDarwin::UnloadAllImages");
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000214 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000215 target.GetImages().Remove(unloaded_modules_list);
216 m_dyld_image_infos.clear();
217 m_dyld_image_infos_stop_id = m_process->GetStopID();
218 }
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000219}
220
Jason Molenda5fe4d142016-07-17 21:27:32 +0000221//----------------------------------------------------------------------
222// Update the load addresses for all segments in MODULE using the
223// updated INFO that is passed in.
224//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000225bool DynamicLoaderDarwin::UpdateImageLoadAddress(Module *module,
226 ImageInfo &info) {
227 bool changed = false;
228 if (module) {
229 ObjectFile *image_object_file = module->GetObjectFile();
230 if (image_object_file) {
231 SectionList *section_list = image_object_file->GetSectionList();
232 if (section_list) {
233 std::vector<uint32_t> inaccessible_segment_indexes;
234 // We now know the slide amount, so go through all sections
235 // and update the load addresses with the correct values.
236 const size_t num_segments = info.segments.size();
237 for (size_t i = 0; i < num_segments; ++i) {
238 // Only load a segment if it has protections. Things like
239 // __PAGEZERO don't have any protections, and they shouldn't
240 // be slid
241 SectionSP section_sp(
242 section_list->FindSectionByName(info.segments[i].name));
Jason Molenda5fe4d142016-07-17 21:27:32 +0000243
Kate Stoneb9c1b512016-09-06 20:57:50 +0000244 if (info.segments[i].maxprot == 0) {
245 inaccessible_segment_indexes.push_back(i);
246 } else {
247 const addr_t new_section_load_addr =
248 info.segments[i].vmaddr + info.slide;
249 static ConstString g_section_name_LINKEDIT("__LINKEDIT");
Jason Molenda5fe4d142016-07-17 21:27:32 +0000250
Kate Stoneb9c1b512016-09-06 20:57:50 +0000251 if (section_sp) {
252 // __LINKEDIT sections from files in the shared cache
253 // can overlap so check to see what the segment name is
254 // and pass "false" so we don't warn of overlapping
255 // "Section" objects, and "true" for all other sections.
256 const bool warn_multiple =
257 section_sp->GetName() != g_section_name_LINKEDIT;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000258
Kate Stoneb9c1b512016-09-06 20:57:50 +0000259 changed = m_process->GetTarget().SetSectionLoadAddress(
260 section_sp, new_section_load_addr, warn_multiple);
261 } else {
262 Host::SystemLog(
263 Host::eSystemLogWarning,
264 "warning: unable to find and load segment named '%s' at "
265 "0x%" PRIx64 " in '%s' in macosx dynamic loader plug-in.\n",
266 info.segments[i].name.AsCString("<invalid>"),
267 (uint64_t)new_section_load_addr,
268 image_object_file->GetFileSpec().GetPath().c_str());
Jason Molenda5fe4d142016-07-17 21:27:32 +0000269 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000270 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000271 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000272
273 // If the loaded the file (it changed) and we have segments that
274 // are not readable or writeable, add them to the invalid memory
275 // region cache for the process. This will typically only be
276 // the __PAGEZERO segment in the main executable. We might be able
277 // to apply this more generally to more sections that have no
278 // protections in the future, but for now we are going to just
279 // do __PAGEZERO.
280 if (changed && !inaccessible_segment_indexes.empty()) {
281 for (uint32_t i = 0; i < inaccessible_segment_indexes.size(); ++i) {
282 const uint32_t seg_idx = inaccessible_segment_indexes[i];
283 SectionSP section_sp(
284 section_list->FindSectionByName(info.segments[seg_idx].name));
285
286 if (section_sp) {
287 static ConstString g_pagezero_section_name("__PAGEZERO");
288 if (g_pagezero_section_name == section_sp->GetName()) {
289 // __PAGEZERO never slides...
290 const lldb::addr_t vmaddr = info.segments[seg_idx].vmaddr;
291 const lldb::addr_t vmsize = info.segments[seg_idx].vmsize;
292 Process::LoadRange pagezero_range(vmaddr, vmsize);
293 m_process->AddInvalidMemoryRegion(pagezero_range);
294 }
295 }
296 }
297 }
298 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000299 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000300 }
301 // We might have an in memory image that was loaded as soon as it was created
302 if (info.load_stop_id == m_process->GetStopID())
303 changed = true;
304 else if (changed) {
305 // Update the stop ID when this library was updated
306 info.load_stop_id = m_process->GetStopID();
307 }
308 return changed;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000309}
310
311//----------------------------------------------------------------------
312// Unload the segments in MODULE using the INFO that is passed in.
313//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000314bool DynamicLoaderDarwin::UnloadModuleSections(Module *module,
315 ImageInfo &info) {
316 bool changed = false;
317 if (module) {
318 ObjectFile *image_object_file = module->GetObjectFile();
319 if (image_object_file) {
320 SectionList *section_list = image_object_file->GetSectionList();
321 if (section_list) {
322 const size_t num_segments = info.segments.size();
323 for (size_t i = 0; i < num_segments; ++i) {
324 SectionSP section_sp(
325 section_list->FindSectionByName(info.segments[i].name));
326 if (section_sp) {
327 const addr_t old_section_load_addr =
328 info.segments[i].vmaddr + info.slide;
329 if (m_process->GetTarget().SetSectionUnloaded(
330 section_sp, old_section_load_addr))
331 changed = true;
332 } else {
333 Host::SystemLog(Host::eSystemLogWarning,
334 "warning: unable to find and unload segment named "
335 "'%s' in '%s' in macosx dynamic loader plug-in.\n",
336 info.segments[i].name.AsCString("<invalid>"),
337 image_object_file->GetFileSpec().GetPath().c_str());
338 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000339 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000340 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000341 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000342 }
343 return changed;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000344}
345
Kate Stoneb9c1b512016-09-06 20:57:50 +0000346// Given a JSON dictionary (from debugserver, most likely) of binary images
347// loaded in the inferior
Jason Molenda5fe4d142016-07-17 21:27:32 +0000348// process, add the images to the ImageInfo collection.
349
Kate Stoneb9c1b512016-09-06 20:57:50 +0000350bool DynamicLoaderDarwin::JSONImageInformationIntoImageInfo(
351 StructuredData::ObjectSP image_details,
352 ImageInfo::collection &image_infos) {
353 StructuredData::ObjectSP images_sp =
354 image_details->GetAsDictionary()->GetValueForKey("images");
355 if (images_sp.get() == nullptr)
356 return false;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000357
Kate Stoneb9c1b512016-09-06 20:57:50 +0000358 image_infos.resize(images_sp->GetAsArray()->GetSize());
Jason Molenda5fe4d142016-07-17 21:27:32 +0000359
Kate Stoneb9c1b512016-09-06 20:57:50 +0000360 for (size_t i = 0; i < image_infos.size(); i++) {
361 StructuredData::ObjectSP image_sp =
362 images_sp->GetAsArray()->GetItemAtIndex(i);
363 if (image_sp.get() == nullptr || image_sp->GetAsDictionary() == nullptr)
364 return false;
365 StructuredData::Dictionary *image = image_sp->GetAsDictionary();
366 if (image->HasKey("load_address") == false ||
367 image->HasKey("pathname") == false ||
368 image->HasKey("mod_date") == false ||
369 image->HasKey("mach_header") == false ||
370 image->GetValueForKey("mach_header")->GetAsDictionary() == nullptr ||
371 image->HasKey("segments") == false ||
372 image->GetValueForKey("segments")->GetAsArray() == nullptr ||
373 image->HasKey("uuid") == false) {
374 return false;
375 }
376 image_infos[i].address =
377 image->GetValueForKey("load_address")->GetAsInteger()->GetValue();
378 image_infos[i].mod_date =
379 image->GetValueForKey("mod_date")->GetAsInteger()->GetValue();
380 image_infos[i].file_spec.SetFile(
381 image->GetValueForKey("pathname")->GetAsString()->GetValue().c_str(),
382 false);
Jason Molenda5fe4d142016-07-17 21:27:32 +0000383
Kate Stoneb9c1b512016-09-06 20:57:50 +0000384 StructuredData::Dictionary *mh =
385 image->GetValueForKey("mach_header")->GetAsDictionary();
386 image_infos[i].header.magic =
387 mh->GetValueForKey("magic")->GetAsInteger()->GetValue();
388 image_infos[i].header.cputype =
389 mh->GetValueForKey("cputype")->GetAsInteger()->GetValue();
390 image_infos[i].header.cpusubtype =
391 mh->GetValueForKey("cpusubtype")->GetAsInteger()->GetValue();
392 image_infos[i].header.filetype =
393 mh->GetValueForKey("filetype")->GetAsInteger()->GetValue();
Jason Molenda5fe4d142016-07-17 21:27:32 +0000394
Kate Stoneb9c1b512016-09-06 20:57:50 +0000395 if (image->HasKey("min_version_os_name")) {
396 std::string os_name = image->GetValueForKey("min_version_os_name")
397 ->GetAsString()
398 ->GetValue();
399 if (os_name == "macosx")
400 image_infos[i].os_type = llvm::Triple::MacOSX;
401 else if (os_name == "ios" || os_name == "iphoneos")
402 image_infos[i].os_type = llvm::Triple::IOS;
403 else if (os_name == "tvos")
404 image_infos[i].os_type = llvm::Triple::TvOS;
405 else if (os_name == "watchos")
406 image_infos[i].os_type = llvm::Triple::WatchOS;
407 }
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
416 // currently send them
417 // in the reply.
418
419 if (mh->HasKey("flags"))
420 image_infos[i].header.flags =
421 mh->GetValueForKey("flags")->GetAsInteger()->GetValue();
422 else
423 image_infos[i].header.flags = 0;
424
425 if (mh->HasKey("ncmds"))
426 image_infos[i].header.ncmds =
427 mh->GetValueForKey("ncmds")->GetAsInteger()->GetValue();
428 else
429 image_infos[i].header.ncmds = 0;
430
431 if (mh->HasKey("sizeofcmds"))
432 image_infos[i].header.sizeofcmds =
433 mh->GetValueForKey("sizeofcmds")->GetAsInteger()->GetValue();
434 else
435 image_infos[i].header.sizeofcmds = 0;
436
437 StructuredData::Array *segments =
438 image->GetValueForKey("segments")->GetAsArray();
439 uint32_t segcount = segments->GetSize();
440 for (size_t j = 0; j < segcount; j++) {
441 Segment segment;
442 StructuredData::Dictionary *seg =
443 segments->GetItemAtIndex(j)->GetAsDictionary();
444 segment.name = ConstString(
445 seg->GetValueForKey("name")->GetAsString()->GetValue().c_str());
446 segment.vmaddr =
447 seg->GetValueForKey("vmaddr")->GetAsInteger()->GetValue();
448 segment.vmsize =
449 seg->GetValueForKey("vmsize")->GetAsInteger()->GetValue();
450 segment.fileoff =
451 seg->GetValueForKey("fileoff")->GetAsInteger()->GetValue();
452 segment.filesize =
453 seg->GetValueForKey("filesize")->GetAsInteger()->GetValue();
454 segment.maxprot =
455 seg->GetValueForKey("maxprot")->GetAsInteger()->GetValue();
456
457 // Fields that aren't used by DynamicLoaderDarwin so debugserver doesn't
458 // currently send them
459 // in the reply.
460
461 if (seg->HasKey("initprot"))
462 segment.initprot =
463 seg->GetValueForKey("initprot")->GetAsInteger()->GetValue();
464 else
465 segment.initprot = 0;
466
467 if (seg->HasKey("flags"))
468 segment.flags =
469 seg->GetValueForKey("flags")->GetAsInteger()->GetValue();
470 else
471 segment.flags = 0;
472
473 if (seg->HasKey("nsects"))
474 segment.nsects =
475 seg->GetValueForKey("nsects")->GetAsInteger()->GetValue();
476 else
477 segment.nsects = 0;
478
479 image_infos[i].segments.push_back(segment);
480 }
481
482 image_infos[i].uuid.SetFromCString(
483 image->GetValueForKey("uuid")->GetAsString()->GetValue().c_str());
484
485 // All sections listed in the dyld image info structure will all
486 // either be fixed up already, or they will all be off by a single
487 // slide amount that is determined by finding the first segment
488 // that is at file offset zero which also has bytes (a file size
489 // that is greater than zero) in the object file.
490
491 // Determine the slide amount (if any)
492 const size_t num_sections = image_infos[i].segments.size();
493 for (size_t k = 0; k < num_sections; ++k) {
494 // Iterate through the object file sections to find the
495 // first section that starts of file offset zero and that
496 // has bytes in the file...
497 if ((image_infos[i].segments[k].fileoff == 0 &&
498 image_infos[i].segments[k].filesize > 0) ||
499 (image_infos[i].segments[k].name == ConstString("__TEXT"))) {
500 image_infos[i].slide =
501 image_infos[i].address - image_infos[i].segments[k].vmaddr;
502 // We have found the slide amount, so we can exit
503 // this for loop.
504 break;
505 }
506 }
507 }
508
509 return true;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000510}
511
Kate Stoneb9c1b512016-09-06 20:57:50 +0000512void DynamicLoaderDarwin::UpdateSpecialBinariesFromNewImageInfos(
513 ImageInfo::collection &image_infos) {
514 uint32_t exe_idx = UINT32_MAX;
515 uint32_t dyld_idx = UINT32_MAX;
516 Target &target = m_process->GetTarget();
517 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
518 ConstString g_dyld_sim_filename("dyld_sim");
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000519
Kate Stoneb9c1b512016-09-06 20:57:50 +0000520 ArchSpec target_arch = target.GetArchitecture();
521 const size_t image_infos_size = image_infos.size();
522 for (size_t i = 0; i < image_infos_size; i++) {
523 if (image_infos[i].header.filetype == llvm::MachO::MH_DYLINKER) {
524 // In a "simulator" process (an x86 process that is ios/tvos/watchos)
525 // we will have two dyld modules -- a "dyld" that we want to keep track
526 // of,
527 // and a "dyld_sim" which we don't need to keep track of here.
528 // If the target is an x86 system and the OS of the dyld binary is
529 // ios/tvos/watchos, then we are looking at dyld_sym.
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000530
Kate Stoneb9c1b512016-09-06 20:57:50 +0000531 // debugserver has only recently (late 2016) started sending up the
532 // os type for each binary it sees -- so if we don't have an os
533 // type, use a filename check as our next best guess.
534 if (image_infos[i].os_type == llvm::Triple::OSType::UnknownOS) {
535 if (image_infos[i].file_spec.GetFilename() != g_dyld_sim_filename) {
536 dyld_idx = i;
537 }
538 } else if (target_arch.GetTriple().getArch() == llvm::Triple::x86 ||
539 target_arch.GetTriple().getArch() == llvm::Triple::x86_64) {
540 if (image_infos[i].os_type != llvm::Triple::OSType::IOS &&
541 image_infos[i].os_type != llvm::Triple::TvOS &&
542 image_infos[i].os_type != llvm::Triple::WatchOS) {
543 dyld_idx = i;
544 }
545 }
546 } else if (image_infos[i].header.filetype == llvm::MachO::MH_EXECUTE) {
547 exe_idx = i;
548 }
549 }
550
551 if (exe_idx != UINT32_MAX) {
552 const bool can_create = true;
553 ModuleSP exe_module_sp(
554 FindTargetModuleForImageInfo(image_infos[exe_idx], can_create, NULL));
555 if (exe_module_sp) {
556 if (log)
557 log->Printf("Found executable module: %s",
558 exe_module_sp->GetFileSpec().GetPath().c_str());
559 target.GetImages().AppendIfNeeded(exe_module_sp);
560 UpdateImageLoadAddress(exe_module_sp.get(), image_infos[exe_idx]);
561 if (exe_module_sp.get() != target.GetExecutableModulePointer()) {
562 const bool get_dependent_images = false;
563 target.SetExecutableModule(exe_module_sp, get_dependent_images);
564 }
565 }
566 }
567
568 if (dyld_idx != UINT32_MAX) {
569 const bool can_create = true;
570 ModuleSP dyld_sp =
571 FindTargetModuleForImageInfo(image_infos[dyld_idx], can_create, NULL);
572 if (dyld_sp.get()) {
573 if (log)
574 log->Printf("Found dyld module: %s",
575 dyld_sp->GetFileSpec().GetPath().c_str());
576 target.GetImages().AppendIfNeeded(dyld_sp);
577 UpdateImageLoadAddress(dyld_sp.get(), image_infos[dyld_idx]);
578 SetDYLDModule(dyld_sp);
579 }
580 }
581}
582
583void DynamicLoaderDarwin::UpdateDYLDImageInfoFromNewImageInfo(
584 ImageInfo &image_info) {
585 if (image_info.header.filetype == llvm::MachO::MH_DYLINKER) {
586 const bool can_create = true;
587 ModuleSP dyld_sp =
588 FindTargetModuleForImageInfo(image_info, can_create, NULL);
589 if (dyld_sp.get()) {
590 Target &target = m_process->GetTarget();
591 target.GetImages().AppendIfNeeded(dyld_sp);
592 UpdateImageLoadAddress(dyld_sp.get(), image_info);
593 SetDYLDModule(dyld_sp);
594 }
595 }
596}
597
598void DynamicLoaderDarwin::SetDYLDModule(lldb::ModuleSP &dyld_module_sp) {
599 m_dyld_module_wp = dyld_module_sp;
600}
601
602ModuleSP DynamicLoaderDarwin::GetDYLDModule() {
603 ModuleSP dyld_sp(m_dyld_module_wp.lock());
604 return dyld_sp;
605}
606
607bool DynamicLoaderDarwin::AddModulesUsingImageInfos(
608 ImageInfo::collection &image_infos) {
609 std::lock_guard<std::recursive_mutex> guard(m_mutex);
610 // Now add these images to the main list.
611 ModuleList loaded_module_list;
612 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
613 Target &target = m_process->GetTarget();
614 ModuleList &target_images = target.GetImages();
615
616 for (uint32_t idx = 0; idx < image_infos.size(); ++idx) {
617 if (log) {
618 log->Printf("Adding new image at address=0x%16.16" PRIx64 ".",
619 image_infos[idx].address);
620 image_infos[idx].PutToLog(log);
621 }
622
623 m_dyld_image_infos.push_back(image_infos[idx]);
624
625 ModuleSP image_module_sp(
626 FindTargetModuleForImageInfo(image_infos[idx], true, NULL));
627
628 if (image_module_sp) {
629 ObjectFile *objfile = image_module_sp->GetObjectFile();
630 if (objfile) {
631 SectionList *sections = objfile->GetSectionList();
632 if (sections) {
633 ConstString commpage_dbstr("__commpage");
634 Section *commpage_section =
635 sections->FindSectionByName(commpage_dbstr).get();
636 if (commpage_section) {
637 ModuleSpec module_spec(objfile->GetFileSpec(),
638 image_infos[idx].GetArchitecture());
639 module_spec.GetObjectName() = commpage_dbstr;
640 ModuleSP commpage_image_module_sp(
641 target_images.FindFirstModule(module_spec));
642 if (!commpage_image_module_sp) {
643 module_spec.SetObjectOffset(objfile->GetFileOffset() +
644 commpage_section->GetFileOffset());
645 module_spec.SetObjectSize(objfile->GetByteSize());
646 commpage_image_module_sp = target.GetSharedModule(module_spec);
647 if (!commpage_image_module_sp ||
648 commpage_image_module_sp->GetObjectFile() == NULL) {
649 commpage_image_module_sp = m_process->ReadModuleFromMemory(
650 image_infos[idx].file_spec, image_infos[idx].address);
651 // Always load a memory image right away in the target in case
652 // we end up trying to read the symbol table from memory... The
653 // __LINKEDIT will need to be mapped so we can figure out where
654 // the symbol table bits are...
655 bool changed = false;
656 UpdateImageLoadAddress(commpage_image_module_sp.get(),
657 image_infos[idx]);
658 target.GetImages().Append(commpage_image_module_sp);
659 if (changed) {
660 image_infos[idx].load_stop_id = m_process->GetStopID();
661 loaded_module_list.AppendIfNeeded(commpage_image_module_sp);
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000662 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000663 }
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000664 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000665 }
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000666 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000667 }
Jason Molenda9ab5dc22016-07-21 08:30:55 +0000668
Kate Stoneb9c1b512016-09-06 20:57:50 +0000669 // UpdateImageLoadAddress will return true if any segments
670 // change load address. We need to check this so we don't
671 // mention that all loaded shared libraries are newly loaded
672 // each time we hit out dyld breakpoint since dyld will list all
673 // shared libraries each time.
674 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
692// functions written in hand-written assembly, and also have hand-written unwind
Kate Stoneb9c1b512016-09-06 20:57:50 +0000693// information in the eh_frame section. Normally we prefer analyzing the
694// assembly instructions of a currently executing frame to unwind from that
695// frame --
Jason Molenda5fe4d142016-07-17 21:27:32 +0000696// but on hand-written functions this profiling can fail. We should use the
697// eh_frame instructions for these functions all the time.
698//
699// As an aside, it would be better if the eh_frame entries had a flag (or were
700// extensible so they could have an Apple-specific flag) which indicates that
701// the instructions are asynchronous -- accurate at every instruction, instead
702// of our normal default assumption that they are not.
703//----------------------------------------------------------------------
704
Kate Stoneb9c1b512016-09-06 20:57:50 +0000705bool DynamicLoaderDarwin::AlwaysRelyOnEHUnwindInfo(SymbolContext &sym_ctx) {
706 ModuleSP module_sp;
707 if (sym_ctx.symbol) {
708 module_sp = sym_ctx.symbol->GetAddressRef().GetModule();
709 }
710 if (module_sp.get() == NULL && sym_ctx.function) {
711 module_sp =
712 sym_ctx.function->GetAddressRange().GetBaseAddress().GetModule();
713 }
714 if (module_sp.get() == NULL)
Jason Molenda5fe4d142016-07-17 21:27:32 +0000715 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000716
717 ObjCLanguageRuntime *objc_runtime = m_process->GetObjCLanguageRuntime();
718 if (objc_runtime != NULL && objc_runtime->IsModuleObjCLibrary(module_sp)) {
719 return true;
720 }
721
722 return false;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000723}
724
Jason Molenda5fe4d142016-07-17 21:27:32 +0000725//----------------------------------------------------------------------
726// Dump a Segment to the file handle provided.
727//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000728void DynamicLoaderDarwin::Segment::PutToLog(Log *log,
729 lldb::addr_t slide) const {
730 if (log) {
731 if (slide == 0)
732 log->Printf("\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ")",
733 name.AsCString(""), vmaddr + slide, vmaddr + slide + vmsize);
734 else
735 log->Printf("\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64
736 ") slide = 0x%" PRIx64,
737 name.AsCString(""), vmaddr + slide, vmaddr + slide + vmsize,
738 slide);
739 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000740}
741
742const DynamicLoaderDarwin::Segment *
Kate Stoneb9c1b512016-09-06 20:57:50 +0000743DynamicLoaderDarwin::ImageInfo::FindSegment(const ConstString &name) const {
744 const size_t num_segments = segments.size();
745 for (size_t i = 0; i < num_segments; ++i) {
746 if (segments[i].name == name)
747 return &segments[i];
748 }
749 return NULL;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000750}
751
Jason Molenda5fe4d142016-07-17 21:27:32 +0000752//----------------------------------------------------------------------
753// Dump an image info structure to the file handle provided.
754//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000755void DynamicLoaderDarwin::ImageInfo::PutToLog(Log *log) const {
756 if (log == NULL)
757 return;
758 const uint8_t *u = (const uint8_t *)uuid.GetBytes();
Jason Molenda5fe4d142016-07-17 21:27:32 +0000759
Kate Stoneb9c1b512016-09-06 20:57:50 +0000760 if (address == LLDB_INVALID_ADDRESS) {
761 if (u) {
762 log->Printf("\t modtime=0x%8.8" PRIx64
763 " uuid=%2.2X%2.2X%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-"
764 "%2.2X%2.2X%2.2X%2.2X%2.2X%2.2X path='%s' (UNLOADED)",
765 mod_date, u[0], u[1], u[2], u[3], u[4], u[5], u[6], u[7],
766 u[8], u[9], u[10], u[11], u[12], u[13], u[14], u[15],
767 file_spec.GetPath().c_str());
768 } else
769 log->Printf("\t modtime=0x%8.8" PRIx64
770 " path='%s' (UNLOADED)",
771 mod_date, file_spec.GetPath().c_str());
772 } else {
773 if (u) {
774 log->Printf("\taddress=0x%16.16" PRIx64 " modtime=0x%8.8" PRIx64
775 " uuid=%2.2X%2.2X%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-"
776 "%2.2X%2.2X%2.2X%2.2X%2.2X%2.2X path='%s'",
777 address, mod_date, u[0], u[1], u[2], u[3], u[4], u[5], u[6],
778 u[7], u[8], u[9], u[10], u[11], u[12], u[13], u[14], u[15],
779 file_spec.GetPath().c_str());
780 } else {
781 log->Printf("\taddress=0x%16.16" PRIx64 " modtime=0x%8.8" PRIx64
782 " path='%s'",
783 address, mod_date, file_spec.GetPath().c_str());
Jason Molenda5fe4d142016-07-17 21:27:32 +0000784 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000785 for (uint32_t i = 0; i < segments.size(); ++i)
786 segments[i].PutToLog(log, slide);
787 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000788}
789
Kate Stoneb9c1b512016-09-06 20:57:50 +0000790void DynamicLoaderDarwin::PrivateInitialize(Process *process) {
791 DEBUG_PRINTF("DynamicLoaderDarwin::%s() process state = %s\n", __FUNCTION__,
792 StateAsCString(m_process->GetState()));
793 Clear(true);
794 m_process = process;
795 m_process->GetTarget().ClearAllLoadedSections();
Jason Molenda5fe4d142016-07-17 21:27:32 +0000796}
797
798//----------------------------------------------------------------------
799// Member function that gets called when the process state changes.
800//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000801void DynamicLoaderDarwin::PrivateProcessStateChanged(Process *process,
802 StateType state) {
803 DEBUG_PRINTF("DynamicLoaderDarwin::%s(%s)\n", __FUNCTION__,
804 StateAsCString(state));
805 switch (state) {
806 case eStateConnected:
807 case eStateAttaching:
808 case eStateLaunching:
809 case eStateInvalid:
810 case eStateUnloaded:
811 case eStateExited:
812 case eStateDetached:
813 Clear(false);
814 break;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000815
Kate Stoneb9c1b512016-09-06 20:57:50 +0000816 case eStateStopped:
817 // Keep trying find dyld and set our notification breakpoint each time
818 // we stop until we succeed
819 if (!DidSetNotificationBreakpoint() && m_process->IsAlive()) {
820 if (NeedToDoInitialImageFetch())
821 DoInitialImageFetch();
Jason Molenda5fe4d142016-07-17 21:27:32 +0000822
Kate Stoneb9c1b512016-09-06 20:57:50 +0000823 SetNotificationBreakpoint();
Jason Molenda5fe4d142016-07-17 21:27:32 +0000824 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000825 break;
826
827 case eStateRunning:
828 case eStateStepping:
829 case eStateCrashed:
830 case eStateSuspended:
831 break;
832 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000833}
834
835ThreadPlanSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000836DynamicLoaderDarwin::GetStepThroughTrampolinePlan(Thread &thread,
837 bool stop_others) {
838 ThreadPlanSP thread_plan_sp;
839 StackFrame *current_frame = thread.GetStackFrameAtIndex(0).get();
840 const SymbolContext &current_context =
841 current_frame->GetSymbolContext(eSymbolContextSymbol);
842 Symbol *current_symbol = current_context.symbol;
843 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
844 TargetSP target_sp(thread.CalculateTarget());
Jason Molenda5fe4d142016-07-17 21:27:32 +0000845
Kate Stoneb9c1b512016-09-06 20:57:50 +0000846 if (current_symbol != NULL) {
847 std::vector<Address> addresses;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000848
Kate Stoneb9c1b512016-09-06 20:57:50 +0000849 if (current_symbol->IsTrampoline()) {
850 const ConstString &trampoline_name = current_symbol->GetMangled().GetName(
851 current_symbol->GetLanguage(), Mangled::ePreferMangled);
Jason Molenda5fe4d142016-07-17 21:27:32 +0000852
Kate Stoneb9c1b512016-09-06 20:57:50 +0000853 if (trampoline_name) {
854 const ModuleList &images = target_sp->GetImages();
855
856 SymbolContextList code_symbols;
857 images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeCode,
858 code_symbols);
859 size_t num_code_symbols = code_symbols.GetSize();
860
861 if (num_code_symbols > 0) {
862 for (uint32_t i = 0; i < num_code_symbols; i++) {
863 SymbolContext context;
864 AddressRange addr_range;
865 if (code_symbols.GetContextAtIndex(i, context)) {
866 context.GetAddressRange(eSymbolContextEverything, 0, false,
867 addr_range);
868 addresses.push_back(addr_range.GetBaseAddress());
869 if (log) {
870 addr_t load_addr =
871 addr_range.GetBaseAddress().GetLoadAddress(target_sp.get());
872
873 log->Printf("Found a trampoline target symbol at 0x%" PRIx64
874 ".",
875 load_addr);
876 }
877 }
878 }
879 }
880
881 SymbolContextList reexported_symbols;
882 images.FindSymbolsWithNameAndType(
883 trampoline_name, eSymbolTypeReExported, reexported_symbols);
884 size_t num_reexported_symbols = reexported_symbols.GetSize();
885 if (num_reexported_symbols > 0) {
886 for (uint32_t i = 0; i < num_reexported_symbols; i++) {
887 SymbolContext context;
888 if (reexported_symbols.GetContextAtIndex(i, context)) {
889 if (context.symbol) {
890 Symbol *actual_symbol =
891 context.symbol->ResolveReExportedSymbol(*target_sp.get());
892 if (actual_symbol) {
893 const Address actual_symbol_addr =
894 actual_symbol->GetAddress();
895 if (actual_symbol_addr.IsValid()) {
896 addresses.push_back(actual_symbol_addr);
897 if (log) {
898 lldb::addr_t load_addr =
899 actual_symbol_addr.GetLoadAddress(target_sp.get());
900 log->Printf(
901 "Found a re-exported symbol: %s at 0x%" PRIx64 ".",
902 actual_symbol->GetName().GetCString(), load_addr);
Jason Molenda5fe4d142016-07-17 21:27:32 +0000903 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000904 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000905 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000906 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000907 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000908 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000909 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000910
911 SymbolContextList indirect_symbols;
912 images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeResolver,
913 indirect_symbols);
914 size_t num_indirect_symbols = indirect_symbols.GetSize();
915 if (num_indirect_symbols > 0) {
916 for (uint32_t i = 0; i < num_indirect_symbols; i++) {
917 SymbolContext context;
918 AddressRange addr_range;
919 if (indirect_symbols.GetContextAtIndex(i, context)) {
920 context.GetAddressRange(eSymbolContextEverything, 0, false,
921 addr_range);
922 addresses.push_back(addr_range.GetBaseAddress());
923 if (log) {
924 addr_t load_addr =
925 addr_range.GetBaseAddress().GetLoadAddress(target_sp.get());
926
927 log->Printf("Found an indirect target symbol at 0x%" PRIx64 ".",
928 load_addr);
929 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000930 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000931 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000932 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000933 }
934 } else if (current_symbol->GetType() == eSymbolTypeReExported) {
935 // I am not sure we could ever end up stopped AT a re-exported symbol.
936 // But just in case:
937
938 const Symbol *actual_symbol =
939 current_symbol->ResolveReExportedSymbol(*(target_sp.get()));
940 if (actual_symbol) {
941 Address target_addr(actual_symbol->GetAddress());
942 if (target_addr.IsValid()) {
943 if (log)
944 log->Printf(
945 "Found a re-exported symbol: %s pointing to: %s at 0x%" PRIx64
946 ".",
947 current_symbol->GetName().GetCString(),
948 actual_symbol->GetName().GetCString(),
949 target_addr.GetLoadAddress(target_sp.get()));
950 addresses.push_back(target_addr.GetLoadAddress(target_sp.get()));
Jason Molenda5fe4d142016-07-17 21:27:32 +0000951 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000952 }
Jason Molenda5fe4d142016-07-17 21:27:32 +0000953 }
954
Kate Stoneb9c1b512016-09-06 20:57:50 +0000955 if (addresses.size() > 0) {
956 // First check whether any of the addresses point to Indirect symbols, and
957 // if they do, resolve them:
958 std::vector<lldb::addr_t> load_addrs;
959 for (Address address : addresses) {
960 Symbol *symbol = address.CalculateSymbolContextSymbol();
961 if (symbol && symbol->IsIndirect()) {
962 Error error;
963 Address symbol_address = symbol->GetAddress();
964 addr_t resolved_addr = thread.GetProcess()->ResolveIndirectFunction(
965 &symbol_address, error);
966 if (error.Success()) {
967 load_addrs.push_back(resolved_addr);
968 if (log)
969 log->Printf("ResolveIndirectFunction found resolved target for "
970 "%s at 0x%" PRIx64 ".",
971 symbol->GetName().GetCString(), resolved_addr);
972 }
973 } else {
974 load_addrs.push_back(address.GetLoadAddress(target_sp.get()));
Jason Molenda5fe4d142016-07-17 21:27:32 +0000975 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000976 }
977 thread_plan_sp.reset(
978 new ThreadPlanRunToAddress(thread, load_addrs, stop_others));
Jason Molenda5fe4d142016-07-17 21:27:32 +0000979 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000980 } else {
981 if (log)
982 log->Printf("Could not find symbol for step through.");
983 }
984
985 return thread_plan_sp;
Jason Molenda5fe4d142016-07-17 21:27:32 +0000986}
987
Kate Stoneb9c1b512016-09-06 20:57:50 +0000988size_t DynamicLoaderDarwin::FindEquivalentSymbols(
989 lldb_private::Symbol *original_symbol, lldb_private::ModuleList &images,
990 lldb_private::SymbolContextList &equivalent_symbols) {
991 const ConstString &trampoline_name = original_symbol->GetMangled().GetName(
992 original_symbol->GetLanguage(), Mangled::ePreferMangled);
993 if (!trampoline_name)
994 return 0;
995
996 size_t initial_size = equivalent_symbols.GetSize();
997
998 static const char *resolver_name_regex = "(_gc|_non_gc|\\$[A-Za-z0-9\\$]+)$";
999 std::string equivalent_regex_buf("^");
1000 equivalent_regex_buf.append(trampoline_name.GetCString());
1001 equivalent_regex_buf.append(resolver_name_regex);
1002
Zachary Turner95eae422016-09-21 16:01:28 +00001003 RegularExpression equivalent_name_regex(equivalent_regex_buf);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001004 const bool append = true;
1005 images.FindSymbolsMatchingRegExAndType(equivalent_name_regex, eSymbolTypeCode,
1006 equivalent_symbols, append);
1007
1008 return equivalent_symbols.GetSize() - initial_size;
1009}
1010
1011lldb::ModuleSP DynamicLoaderDarwin::GetPThreadLibraryModule() {
1012 ModuleSP module_sp = m_libpthread_module_wp.lock();
1013 if (!module_sp) {
1014 SymbolContextList sc_list;
1015 ModuleSpec module_spec;
1016 module_spec.GetFileSpec().GetFilename().SetCString(
1017 "libsystem_pthread.dylib");
1018 ModuleList module_list;
1019 if (m_process->GetTarget().GetImages().FindModules(module_spec,
1020 module_list)) {
1021 if (module_list.GetSize() == 1) {
1022 module_sp = module_list.GetModuleAtIndex(0);
Jason Molenda5fe4d142016-07-17 21:27:32 +00001023 if (module_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001024 m_libpthread_module_wp = module_sp;
1025 }
Jason Molenda5fe4d142016-07-17 21:27:32 +00001026 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001027 }
1028 return module_sp;
1029}
1030
1031Address DynamicLoaderDarwin::GetPthreadSetSpecificAddress() {
1032 if (!m_pthread_getspecific_addr.IsValid()) {
1033 ModuleSP module_sp = GetPThreadLibraryModule();
1034 if (module_sp) {
1035 lldb_private::SymbolContextList sc_list;
1036 module_sp->FindSymbolsWithNameAndType(ConstString("pthread_getspecific"),
1037 eSymbolTypeCode, sc_list);
1038 SymbolContext sc;
1039 if (sc_list.GetContextAtIndex(0, sc)) {
1040 if (sc.symbol)
1041 m_pthread_getspecific_addr = sc.symbol->GetAddress();
1042 }
1043 }
1044 }
1045 return m_pthread_getspecific_addr;
Jason Molenda5fe4d142016-07-17 21:27:32 +00001046}
1047
1048lldb::addr_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001049DynamicLoaderDarwin::GetThreadLocalData(const lldb::ModuleSP module_sp,
1050 const lldb::ThreadSP thread_sp,
1051 lldb::addr_t tls_file_addr) {
1052 if (!thread_sp || !module_sp)
Jason Molenda5fe4d142016-07-17 21:27:32 +00001053 return LLDB_INVALID_ADDRESS;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001054
1055 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1056
1057 const uint32_t addr_size = m_process->GetAddressByteSize();
1058 uint8_t buf[sizeof(lldb::addr_t) * 3];
1059
1060 lldb_private::Address tls_addr;
1061 if (module_sp->ResolveFileAddress(tls_file_addr, tls_addr)) {
1062 Error error;
1063 const size_t tsl_data_size = addr_size * 3;
1064 Target &target = m_process->GetTarget();
1065 if (target.ReadMemory(tls_addr, false, buf, tsl_data_size, error) ==
1066 tsl_data_size) {
1067 const ByteOrder byte_order = m_process->GetByteOrder();
1068 DataExtractor data(buf, sizeof(buf), byte_order, addr_size);
1069 lldb::offset_t offset = addr_size; // Skip the first pointer
1070 const lldb::addr_t pthread_key = data.GetAddress(&offset);
1071 const lldb::addr_t tls_offset = data.GetAddress(&offset);
1072 if (pthread_key != 0) {
1073 // First check to see if we have already figured out the location
1074 // of TLS data for the pthread_key on a specific thread yet. If we
1075 // have we can re-use it since its location will not change unless
1076 // the process execs.
1077 const tid_t tid = thread_sp->GetID();
1078 auto tid_pos = m_tid_to_tls_map.find(tid);
1079 if (tid_pos != m_tid_to_tls_map.end()) {
1080 auto tls_pos = tid_pos->second.find(pthread_key);
1081 if (tls_pos != tid_pos->second.end()) {
1082 return tls_pos->second + tls_offset;
1083 }
1084 }
1085 StackFrameSP frame_sp = thread_sp->GetStackFrameAtIndex(0);
1086 if (frame_sp) {
1087 ClangASTContext *clang_ast_context =
1088 target.GetScratchClangASTContext();
1089
1090 if (!clang_ast_context)
1091 return LLDB_INVALID_ADDRESS;
1092
1093 CompilerType clang_void_ptr_type =
1094 clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
1095 Address pthread_getspecific_addr = GetPthreadSetSpecificAddress();
1096 if (pthread_getspecific_addr.IsValid()) {
1097 EvaluateExpressionOptions options;
1098
1099 lldb::ThreadPlanSP thread_plan_sp(new ThreadPlanCallFunction(
1100 *thread_sp, pthread_getspecific_addr, clang_void_ptr_type,
1101 llvm::ArrayRef<lldb::addr_t>(pthread_key), options));
1102
1103 DiagnosticManager execution_errors;
1104 ExecutionContext exe_ctx(thread_sp);
1105 lldb::ExpressionResults results = m_process->RunThreadPlan(
1106 exe_ctx, thread_plan_sp, options, execution_errors);
1107
1108 if (results == lldb::eExpressionCompleted) {
1109 lldb::ValueObjectSP result_valobj_sp =
1110 thread_plan_sp->GetReturnValueObject();
1111 if (result_valobj_sp) {
1112 const lldb::addr_t pthread_key_data =
1113 result_valobj_sp->GetValueAsUnsigned(0);
1114 if (pthread_key_data) {
1115 m_tid_to_tls_map[tid].insert(
1116 std::make_pair(pthread_key, pthread_key_data));
1117 return pthread_key_data + tls_offset;
1118 }
1119 }
1120 }
1121 }
1122 }
1123 }
1124 }
1125 }
1126 return LLDB_INVALID_ADDRESS;
Jason Molenda5fe4d142016-07-17 21:27:32 +00001127}
1128
Kate Stoneb9c1b512016-09-06 20:57:50 +00001129bool DynamicLoaderDarwin::UseDYLDSPI(Process *process) {
1130 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
1131 uint32_t major, minor, update;
Jason Molenda9ab5dc22016-07-21 08:30:55 +00001132
Kate Stoneb9c1b512016-09-06 20:57:50 +00001133 bool use_new_spi_interface = false;
Jason Molenda9ab5dc22016-07-21 08:30:55 +00001134
Kate Stoneb9c1b512016-09-06 20:57:50 +00001135 if (process->GetHostOSVersion(major, minor, update)) {
1136 const llvm::Triple::OSType os_type =
1137 process->GetTarget().GetArchitecture().GetTriple().getOS();
Jason Molenda9ab5dc22016-07-21 08:30:55 +00001138
Kate Stoneb9c1b512016-09-06 20:57:50 +00001139 // macOS 10.12 and newer
1140 if (os_type == llvm::Triple::MacOSX &&
1141 (major >= 10 || (major == 10 && minor >= 12))) {
1142 use_new_spi_interface = true;
Jason Molenda9ab5dc22016-07-21 08:30:55 +00001143 }
1144
Kate Stoneb9c1b512016-09-06 20:57:50 +00001145 // iOS 10 and newer
1146 if (os_type == llvm::Triple::IOS && major >= 10) {
1147 use_new_spi_interface = true;
Jason Molenda9ab5dc22016-07-21 08:30:55 +00001148 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001149
1150 // tvOS 10 and newer
1151 if (os_type == llvm::Triple::TvOS && major >= 10) {
1152 use_new_spi_interface = true;
1153 }
1154
1155 // watchOS 3 and newer
1156 if (os_type == llvm::Triple::WatchOS && major >= 3) {
1157 use_new_spi_interface = true;
1158 }
1159 }
1160
Kate Stoneb9c1b512016-09-06 20:57:50 +00001161 if (log) {
1162 if (use_new_spi_interface)
1163 log->Printf(
1164 "DynamicLoaderDarwin::UseDYLDSPI: Use new DynamicLoader plugin");
1165 else
1166 log->Printf(
1167 "DynamicLoaderDarwin::UseDYLDSPI: Use old DynamicLoader plugin");
1168 }
1169 return use_new_spi_interface;
Jason Molenda9ab5dc22016-07-21 08:30:55 +00001170}