1 //===-- DynamicLoaderDarwin.cpp -------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "DynamicLoaderDarwin.h"
10
11 #include "lldb/Breakpoint/StoppointCallbackContext.h"
12 #include "lldb/Core/Debugger.h"
13 #include "lldb/Core/Module.h"
14 #include "lldb/Core/ModuleSpec.h"
15 #include "lldb/Core/PluginManager.h"
16 #include "lldb/Core/Section.h"
17 #include "lldb/Expression/DiagnosticManager.h"
18 #include "lldb/Host/FileSystem.h"
19 #include "lldb/Host/HostInfo.h"
20 #include "lldb/Symbol/Function.h"
21 #include "lldb/Symbol/ObjectFile.h"
22 #include "lldb/Target/ABI.h"
23 #include "lldb/Target/RegisterContext.h"
24 #include "lldb/Target/StackFrame.h"
25 #include "lldb/Target/Target.h"
26 #include "lldb/Target/Thread.h"
27 #include "lldb/Target/ThreadPlanCallFunction.h"
28 #include "lldb/Target/ThreadPlanRunToAddress.h"
29 #include "lldb/Utility/DataBuffer.h"
30 #include "lldb/Utility/DataBufferHeap.h"
31 #include "lldb/Utility/LLDBLog.h"
32 #include "lldb/Utility/Log.h"
33 #include "lldb/Utility/State.h"
34
35 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
36 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
37
38 //#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN
39 #ifdef ENABLE_DEBUG_PRINTF
40 #include <cstdio>
41 #define DEBUG_PRINTF(fmt, ...) printf(fmt, ##__VA_ARGS__)
42 #else
43 #define DEBUG_PRINTF(fmt, ...)
44 #endif
45
46 #ifndef __APPLE__
47 #include "Utility/UuidCompatibility.h"
48 #else
49 #include <uuid/uuid.h>
50 #endif
51
52 #include <memory>
53
54 using namespace lldb;
55 using namespace lldb_private;
56
57 // Constructor
DynamicLoaderDarwin(Process * process)58 DynamicLoaderDarwin::DynamicLoaderDarwin(Process *process)
59 : DynamicLoader(process), m_dyld_module_wp(), m_libpthread_module_wp(),
60 m_pthread_getspecific_addr(), m_tid_to_tls_map(), m_dyld_image_infos(),
61 m_dyld_image_infos_stop_id(UINT32_MAX), m_dyld(), m_mutex() {}
62
63 // Destructor
64 DynamicLoaderDarwin::~DynamicLoaderDarwin() = default;
65
66 /// Called after attaching a process.
67 ///
68 /// Allow DynamicLoader plug-ins to execute some code after
69 /// attaching to a process.
DidAttach()70 void DynamicLoaderDarwin::DidAttach() {
71 PrivateInitialize(m_process);
72 DoInitialImageFetch();
73 SetNotificationBreakpoint();
74 }
75
76 /// Called after attaching a process.
77 ///
78 /// Allow DynamicLoader plug-ins to execute some code after
79 /// attaching to a process.
DidLaunch()80 void DynamicLoaderDarwin::DidLaunch() {
81 PrivateInitialize(m_process);
82 DoInitialImageFetch();
83 SetNotificationBreakpoint();
84 }
85
86 // Clear out the state of this class.
Clear(bool clear_process)87 void DynamicLoaderDarwin::Clear(bool clear_process) {
88 std::lock_guard<std::recursive_mutex> guard(m_mutex);
89 if (clear_process)
90 m_process = nullptr;
91 m_dyld_image_infos.clear();
92 m_dyld_image_infos_stop_id = UINT32_MAX;
93 m_dyld.Clear(false);
94 }
95
FindTargetModuleForImageInfo(ImageInfo & image_info,bool can_create,bool * did_create_ptr)96 ModuleSP DynamicLoaderDarwin::FindTargetModuleForImageInfo(
97 ImageInfo &image_info, bool can_create, bool *did_create_ptr) {
98 if (did_create_ptr)
99 *did_create_ptr = false;
100
101 Target &target = m_process->GetTarget();
102 const ModuleList &target_images = target.GetImages();
103 ModuleSpec module_spec(image_info.file_spec);
104 module_spec.GetUUID() = image_info.uuid;
105
106 // macCatalyst support: Request matching os/environment.
107 {
108 auto &target_triple = target.GetArchitecture().GetTriple();
109 if (target_triple.getOS() == llvm::Triple::IOS &&
110 target_triple.getEnvironment() == llvm::Triple::MacABI) {
111 // Request the macCatalyst variant of frameworks that have both
112 // a PLATFORM_MACOS and a PLATFORM_MACCATALYST load command.
113 module_spec.GetArchitecture() = ArchSpec(target_triple);
114 }
115 }
116
117 ModuleSP module_sp(target_images.FindFirstModule(module_spec));
118
119 if (module_sp && !module_spec.GetUUID().IsValid() &&
120 !module_sp->GetUUID().IsValid()) {
121 // No UUID, we must rely upon the cached module modification time and the
122 // modification time of the file on disk
123 if (module_sp->GetModificationTime() !=
124 FileSystem::Instance().GetModificationTime(module_sp->GetFileSpec()))
125 module_sp.reset();
126 }
127
128 if (module_sp || !can_create)
129 return module_sp;
130
131 if (HostInfo::GetArchitecture().IsCompatibleMatch(target.GetArchitecture())) {
132 // When debugging on the host, we are most likely using the same shared
133 // cache as our inferior. The dylibs from the shared cache might not
134 // exist on the filesystem, so let's use the images in our own memory
135 // to create the modules.
136 // Check if the requested image is in our shared cache.
137 SharedCacheImageInfo image_info =
138 HostInfo::GetSharedCacheImageInfo(module_spec.GetFileSpec().GetPath());
139
140 // If we found it and it has the correct UUID, let's proceed with
141 // creating a module from the memory contents.
142 if (image_info.uuid &&
143 (!module_spec.GetUUID() || module_spec.GetUUID() == image_info.uuid)) {
144 ModuleSpec shared_cache_spec(module_spec.GetFileSpec(), image_info.uuid,
145 image_info.data_sp);
146 module_sp =
147 target.GetOrCreateModule(shared_cache_spec, false /* notify */);
148 }
149 }
150 // We'll call Target::ModulesDidLoad after all the modules have been
151 // added to the target, don't let it be called for every one.
152 if (!module_sp)
153 module_sp = target.GetOrCreateModule(module_spec, false /* notify */);
154 if (!module_sp || module_sp->GetObjectFile() == nullptr)
155 module_sp = m_process->ReadModuleFromMemory(image_info.file_spec,
156 image_info.address);
157
158 if (did_create_ptr)
159 *did_create_ptr = (bool)module_sp;
160
161 return module_sp;
162 }
163
UnloadImages(const std::vector<lldb::addr_t> & solib_addresses)164 void DynamicLoaderDarwin::UnloadImages(
165 const std::vector<lldb::addr_t> &solib_addresses) {
166 std::lock_guard<std::recursive_mutex> guard(m_mutex);
167 if (m_process->GetStopID() == m_dyld_image_infos_stop_id)
168 return;
169
170 Log *log = GetLog(LLDBLog::DynamicLoader);
171 Target &target = m_process->GetTarget();
172 LLDB_LOGF(log, "Removing %" PRId64 " modules.",
173 (uint64_t)solib_addresses.size());
174
175 ModuleList unloaded_module_list;
176
177 for (addr_t solib_addr : solib_addresses) {
178 Address header;
179 if (header.SetLoadAddress(solib_addr, &target)) {
180 if (header.GetOffset() == 0) {
181 ModuleSP module_to_remove(header.GetModule());
182 if (module_to_remove.get()) {
183 LLDB_LOGF(log, "Removing module at address 0x%" PRIx64, solib_addr);
184 // remove the sections from the Target
185 UnloadSections(module_to_remove);
186 // add this to the list of modules to remove
187 unloaded_module_list.AppendIfNeeded(module_to_remove);
188 // remove the entry from the m_dyld_image_infos
189 ImageInfo::collection::iterator pos, end = m_dyld_image_infos.end();
190 for (pos = m_dyld_image_infos.begin(); pos != end; pos++) {
191 if (solib_addr == (*pos).address) {
192 m_dyld_image_infos.erase(pos);
193 break;
194 }
195 }
196 }
197 }
198 }
199 }
200
201 if (unloaded_module_list.GetSize() > 0) {
202 if (log) {
203 log->PutCString("Unloaded:");
204 unloaded_module_list.LogUUIDAndPaths(
205 log, "DynamicLoaderDarwin::UnloadModules");
206 }
207 m_process->GetTarget().GetImages().Remove(unloaded_module_list);
208 m_dyld_image_infos_stop_id = m_process->GetStopID();
209 }
210 }
211
UnloadAllImages()212 void DynamicLoaderDarwin::UnloadAllImages() {
213 Log *log = GetLog(LLDBLog::DynamicLoader);
214 ModuleList unloaded_modules_list;
215
216 Target &target = m_process->GetTarget();
217 const ModuleList &target_modules = target.GetImages();
218 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
219
220 ModuleSP dyld_sp(GetDYLDModule());
221 for (ModuleSP module_sp : target_modules.Modules()) {
222 // Don't remove dyld - else we'll lose our breakpoint notifying us about
223 // libraries being re-loaded...
224 if (module_sp && module_sp != dyld_sp) {
225 UnloadSections(module_sp);
226 unloaded_modules_list.Append(module_sp);
227 }
228 }
229
230 if (unloaded_modules_list.GetSize() != 0) {
231 if (log) {
232 log->PutCString("Unloaded:");
233 unloaded_modules_list.LogUUIDAndPaths(
234 log, "DynamicLoaderDarwin::UnloadAllImages");
235 }
236 target.GetImages().Remove(unloaded_modules_list);
237 m_dyld_image_infos.clear();
238 m_dyld_image_infos_stop_id = m_process->GetStopID();
239 }
240 }
241
242 // Update the load addresses for all segments in MODULE using the updated INFO
243 // that is passed in.
UpdateImageLoadAddress(Module * module,ImageInfo & info)244 bool DynamicLoaderDarwin::UpdateImageLoadAddress(Module *module,
245 ImageInfo &info) {
246 bool changed = false;
247 if (module) {
248 ObjectFile *image_object_file = module->GetObjectFile();
249 if (image_object_file) {
250 SectionList *section_list = image_object_file->GetSectionList();
251 if (section_list) {
252 std::vector<uint32_t> inaccessible_segment_indexes;
253 // We now know the slide amount, so go through all sections and update
254 // the load addresses with the correct values.
255 const size_t num_segments = info.segments.size();
256 for (size_t i = 0; i < num_segments; ++i) {
257 // Only load a segment if it has protections. Things like __PAGEZERO
258 // don't have any protections, and they shouldn't be slid
259 SectionSP section_sp(
260 section_list->FindSectionByName(info.segments[i].name));
261
262 if (info.segments[i].maxprot == 0) {
263 inaccessible_segment_indexes.push_back(i);
264 } else {
265 const addr_t new_section_load_addr =
266 info.segments[i].vmaddr + info.slide;
267 static ConstString g_section_name_LINKEDIT("__LINKEDIT");
268
269 if (section_sp) {
270 // __LINKEDIT sections from files in the shared cache can overlap
271 // so check to see what the segment name is and pass "false" so
272 // we don't warn of overlapping "Section" objects, and "true" for
273 // all other sections.
274 const bool warn_multiple =
275 section_sp->GetName() != g_section_name_LINKEDIT;
276
277 changed = m_process->GetTarget().SetSectionLoadAddress(
278 section_sp, new_section_load_addr, warn_multiple);
279 }
280 }
281 }
282
283 // If the loaded the file (it changed) and we have segments that are
284 // not readable or writeable, add them to the invalid memory region
285 // cache for the process. This will typically only be the __PAGEZERO
286 // segment in the main executable. We might be able to apply this more
287 // generally to more sections that have no protections in the future,
288 // but for now we are going to just do __PAGEZERO.
289 if (changed && !inaccessible_segment_indexes.empty()) {
290 for (uint32_t i = 0; i < inaccessible_segment_indexes.size(); ++i) {
291 const uint32_t seg_idx = inaccessible_segment_indexes[i];
292 SectionSP section_sp(
293 section_list->FindSectionByName(info.segments[seg_idx].name));
294
295 if (section_sp) {
296 static ConstString g_pagezero_section_name("__PAGEZERO");
297 if (g_pagezero_section_name == section_sp->GetName()) {
298 // __PAGEZERO never slides...
299 const lldb::addr_t vmaddr = info.segments[seg_idx].vmaddr;
300 const lldb::addr_t vmsize = info.segments[seg_idx].vmsize;
301 Process::LoadRange pagezero_range(vmaddr, vmsize);
302 m_process->AddInvalidMemoryRegion(pagezero_range);
303 }
304 }
305 }
306 }
307 }
308 }
309 }
310 // We might have an in memory image that was loaded as soon as it was created
311 if (info.load_stop_id == m_process->GetStopID())
312 changed = true;
313 else if (changed) {
314 // Update the stop ID when this library was updated
315 info.load_stop_id = m_process->GetStopID();
316 }
317 return changed;
318 }
319
320 // Unload the segments in MODULE using the INFO that is passed in.
UnloadModuleSections(Module * module,ImageInfo & info)321 bool DynamicLoaderDarwin::UnloadModuleSections(Module *module,
322 ImageInfo &info) {
323 bool changed = false;
324 if (module) {
325 ObjectFile *image_object_file = module->GetObjectFile();
326 if (image_object_file) {
327 SectionList *section_list = image_object_file->GetSectionList();
328 if (section_list) {
329 const size_t num_segments = info.segments.size();
330 for (size_t i = 0; i < num_segments; ++i) {
331 SectionSP section_sp(
332 section_list->FindSectionByName(info.segments[i].name));
333 if (section_sp) {
334 const addr_t old_section_load_addr =
335 info.segments[i].vmaddr + info.slide;
336 if (m_process->GetTarget().SetSectionUnloaded(
337 section_sp, old_section_load_addr))
338 changed = true;
339 } else {
340 Debugger::ReportWarning(
341 llvm::formatv("unable to find and unload segment named "
342 "'{0}' in '{1}' in macosx dynamic loader plug-in",
343 info.segments[i].name.AsCString("<invalid>"),
344 image_object_file->GetFileSpec().GetPath()));
345 }
346 }
347 }
348 }
349 }
350 return changed;
351 }
352
353 // Given a JSON dictionary (from debugserver, most likely) of binary images
354 // loaded in the inferior process, add the images to the ImageInfo collection.
355
JSONImageInformationIntoImageInfo(StructuredData::ObjectSP image_details,ImageInfo::collection & image_infos)356 bool DynamicLoaderDarwin::JSONImageInformationIntoImageInfo(
357 StructuredData::ObjectSP image_details,
358 ImageInfo::collection &image_infos) {
359 StructuredData::ObjectSP images_sp =
360 image_details->GetAsDictionary()->GetValueForKey("images");
361 if (images_sp.get() == nullptr)
362 return false;
363
364 image_infos.resize(images_sp->GetAsArray()->GetSize());
365
366 for (size_t i = 0; i < image_infos.size(); i++) {
367 StructuredData::ObjectSP image_sp =
368 images_sp->GetAsArray()->GetItemAtIndex(i);
369 if (image_sp.get() == nullptr || image_sp->GetAsDictionary() == nullptr)
370 return false;
371 StructuredData::Dictionary *image = image_sp->GetAsDictionary();
372 // clang-format off
373 if (!image->HasKey("load_address") ||
374 !image->HasKey("pathname") ||
375 !image->HasKey("mod_date") ||
376 !image->HasKey("mach_header") ||
377 image->GetValueForKey("mach_header")->GetAsDictionary() == nullptr ||
378 !image->HasKey("segments") ||
379 image->GetValueForKey("segments")->GetAsArray() == nullptr ||
380 !image->HasKey("uuid")) {
381 return false;
382 }
383 // clang-format on
384 image_infos[i].address =
385 image->GetValueForKey("load_address")->GetAsInteger()->GetValue();
386 image_infos[i].mod_date =
387 image->GetValueForKey("mod_date")->GetAsInteger()->GetValue();
388 image_infos[i].file_spec.SetFile(
389 image->GetValueForKey("pathname")->GetAsString()->GetValue(),
390 FileSpec::Style::native);
391
392 StructuredData::Dictionary *mh =
393 image->GetValueForKey("mach_header")->GetAsDictionary();
394 image_infos[i].header.magic =
395 mh->GetValueForKey("magic")->GetAsInteger()->GetValue();
396 image_infos[i].header.cputype =
397 mh->GetValueForKey("cputype")->GetAsInteger()->GetValue();
398 image_infos[i].header.cpusubtype =
399 mh->GetValueForKey("cpusubtype")->GetAsInteger()->GetValue();
400 image_infos[i].header.filetype =
401 mh->GetValueForKey("filetype")->GetAsInteger()->GetValue();
402
403 if (image->HasKey("min_version_os_name")) {
404 std::string os_name =
405 std::string(image->GetValueForKey("min_version_os_name")
406 ->GetAsString()
407 ->GetValue());
408 if (os_name == "macosx")
409 image_infos[i].os_type = llvm::Triple::MacOSX;
410 else if (os_name == "ios" || os_name == "iphoneos")
411 image_infos[i].os_type = llvm::Triple::IOS;
412 else if (os_name == "tvos")
413 image_infos[i].os_type = llvm::Triple::TvOS;
414 else if (os_name == "watchos")
415 image_infos[i].os_type = llvm::Triple::WatchOS;
416 // NEED_BRIDGEOS_TRIPLE else if (os_name == "bridgeos")
417 // NEED_BRIDGEOS_TRIPLE image_infos[i].os_type = llvm::Triple::BridgeOS;
418 else if (os_name == "maccatalyst") {
419 image_infos[i].os_type = llvm::Triple::IOS;
420 image_infos[i].os_env = llvm::Triple::MacABI;
421 } else if (os_name == "iossimulator") {
422 image_infos[i].os_type = llvm::Triple::IOS;
423 image_infos[i].os_env = llvm::Triple::Simulator;
424 } else if (os_name == "tvossimulator") {
425 image_infos[i].os_type = llvm::Triple::TvOS;
426 image_infos[i].os_env = llvm::Triple::Simulator;
427 } else if (os_name == "watchossimulator") {
428 image_infos[i].os_type = llvm::Triple::WatchOS;
429 image_infos[i].os_env = llvm::Triple::Simulator;
430 }
431 }
432 if (image->HasKey("min_version_os_sdk")) {
433 image_infos[i].min_version_os_sdk =
434 std::string(image->GetValueForKey("min_version_os_sdk")
435 ->GetAsString()
436 ->GetValue());
437 }
438
439 // Fields that aren't used by DynamicLoaderDarwin so debugserver doesn't
440 // currently send them in the reply.
441
442 if (mh->HasKey("flags"))
443 image_infos[i].header.flags =
444 mh->GetValueForKey("flags")->GetAsInteger()->GetValue();
445 else
446 image_infos[i].header.flags = 0;
447
448 if (mh->HasKey("ncmds"))
449 image_infos[i].header.ncmds =
450 mh->GetValueForKey("ncmds")->GetAsInteger()->GetValue();
451 else
452 image_infos[i].header.ncmds = 0;
453
454 if (mh->HasKey("sizeofcmds"))
455 image_infos[i].header.sizeofcmds =
456 mh->GetValueForKey("sizeofcmds")->GetAsInteger()->GetValue();
457 else
458 image_infos[i].header.sizeofcmds = 0;
459
460 StructuredData::Array *segments =
461 image->GetValueForKey("segments")->GetAsArray();
462 uint32_t segcount = segments->GetSize();
463 for (size_t j = 0; j < segcount; j++) {
464 Segment segment;
465 StructuredData::Dictionary *seg =
466 segments->GetItemAtIndex(j)->GetAsDictionary();
467 segment.name =
468 ConstString(seg->GetValueForKey("name")->GetAsString()->GetValue());
469 segment.vmaddr =
470 seg->GetValueForKey("vmaddr")->GetAsInteger()->GetValue();
471 segment.vmsize =
472 seg->GetValueForKey("vmsize")->GetAsInteger()->GetValue();
473 segment.fileoff =
474 seg->GetValueForKey("fileoff")->GetAsInteger()->GetValue();
475 segment.filesize =
476 seg->GetValueForKey("filesize")->GetAsInteger()->GetValue();
477 segment.maxprot =
478 seg->GetValueForKey("maxprot")->GetAsInteger()->GetValue();
479
480 // Fields that aren't used by DynamicLoaderDarwin so debugserver doesn't
481 // currently send them in the reply.
482
483 if (seg->HasKey("initprot"))
484 segment.initprot =
485 seg->GetValueForKey("initprot")->GetAsInteger()->GetValue();
486 else
487 segment.initprot = 0;
488
489 if (seg->HasKey("flags"))
490 segment.flags =
491 seg->GetValueForKey("flags")->GetAsInteger()->GetValue();
492 else
493 segment.flags = 0;
494
495 if (seg->HasKey("nsects"))
496 segment.nsects =
497 seg->GetValueForKey("nsects")->GetAsInteger()->GetValue();
498 else
499 segment.nsects = 0;
500
501 image_infos[i].segments.push_back(segment);
502 }
503
504 image_infos[i].uuid.SetFromStringRef(
505 image->GetValueForKey("uuid")->GetAsString()->GetValue());
506
507 // All sections listed in the dyld image info structure will all either be
508 // fixed up already, or they will all be off by a single slide amount that
509 // is determined by finding the first segment that is at file offset zero
510 // which also has bytes (a file size that is greater than zero) in the
511 // object file.
512
513 // Determine the slide amount (if any)
514 const size_t num_sections = image_infos[i].segments.size();
515 for (size_t k = 0; k < num_sections; ++k) {
516 // Iterate through the object file sections to find the first section
517 // that starts of file offset zero and that has bytes in the file...
518 if ((image_infos[i].segments[k].fileoff == 0 &&
519 image_infos[i].segments[k].filesize > 0) ||
520 (image_infos[i].segments[k].name == "__TEXT")) {
521 image_infos[i].slide =
522 image_infos[i].address - image_infos[i].segments[k].vmaddr;
523 // We have found the slide amount, so we can exit this for loop.
524 break;
525 }
526 }
527 }
528
529 return true;
530 }
531
UpdateSpecialBinariesFromNewImageInfos(ImageInfo::collection & image_infos)532 void DynamicLoaderDarwin::UpdateSpecialBinariesFromNewImageInfos(
533 ImageInfo::collection &image_infos) {
534 uint32_t exe_idx = UINT32_MAX;
535 uint32_t dyld_idx = UINT32_MAX;
536 Target &target = m_process->GetTarget();
537 Log *log = GetLog(LLDBLog::DynamicLoader);
538 ConstString g_dyld_sim_filename("dyld_sim");
539
540 ArchSpec target_arch = target.GetArchitecture();
541 const size_t image_infos_size = image_infos.size();
542 for (size_t i = 0; i < image_infos_size; i++) {
543 if (image_infos[i].header.filetype == llvm::MachO::MH_DYLINKER) {
544 // In a "simulator" process we will have two dyld modules --
545 // a "dyld" that we want to keep track of, and a "dyld_sim" which
546 // we don't need to keep track of here. dyld_sim will have a non-macosx
547 // OS.
548 if (target_arch.GetTriple().getEnvironment() == llvm::Triple::Simulator &&
549 image_infos[i].os_type != llvm::Triple::OSType::MacOSX) {
550 continue;
551 }
552
553 dyld_idx = i;
554 }
555 if (image_infos[i].header.filetype == llvm::MachO::MH_EXECUTE) {
556 exe_idx = i;
557 }
558 }
559
560 // Set the target executable if we haven't found one so far.
561 if (exe_idx != UINT32_MAX && !target.GetExecutableModule()) {
562 const bool can_create = true;
563 ModuleSP exe_module_sp(FindTargetModuleForImageInfo(image_infos[exe_idx],
564 can_create, nullptr));
565 if (exe_module_sp) {
566 LLDB_LOGF(log, "Found executable module: %s",
567 exe_module_sp->GetFileSpec().GetPath().c_str());
568 target.GetImages().AppendIfNeeded(exe_module_sp);
569 UpdateImageLoadAddress(exe_module_sp.get(), image_infos[exe_idx]);
570 if (exe_module_sp.get() != target.GetExecutableModulePointer())
571 target.SetExecutableModule(exe_module_sp, eLoadDependentsNo);
572
573 // Update the target executable's arch if necessary.
574 auto exe_triple = exe_module_sp->GetArchitecture().GetTriple();
575 if (target_arch.GetTriple().isArm64e() &&
576 exe_triple.getArch() == llvm::Triple::aarch64 &&
577 !exe_triple.isArm64e()) {
578 // On arm64e-capable Apple platforms, the system libraries are
579 // always arm64e, but applications often are arm64. When a
580 // target is created from a file, LLDB recognizes it as an
581 // arm64 target, but debugserver will still (technically
582 // correct) report the process as being arm64e. For
583 // consistency, set the target to arm64 here, so attaching to
584 // a live process behaves the same as creating a process from
585 // file.
586 auto triple = target_arch.GetTriple();
587 triple.setArchName(exe_triple.getArchName());
588 target_arch.SetTriple(triple);
589 target.SetArchitecture(target_arch, /*set_platform=*/false,
590 /*merge=*/false);
591 }
592 }
593 }
594
595 if (dyld_idx != UINT32_MAX) {
596 const bool can_create = true;
597 ModuleSP dyld_sp = FindTargetModuleForImageInfo(image_infos[dyld_idx],
598 can_create, nullptr);
599 if (dyld_sp.get()) {
600 LLDB_LOGF(log, "Found dyld module: %s",
601 dyld_sp->GetFileSpec().GetPath().c_str());
602 target.GetImages().AppendIfNeeded(dyld_sp);
603 UpdateImageLoadAddress(dyld_sp.get(), image_infos[dyld_idx]);
604 SetDYLDModule(dyld_sp);
605 }
606 }
607 }
608
UpdateDYLDImageInfoFromNewImageInfo(ImageInfo & image_info)609 void DynamicLoaderDarwin::UpdateDYLDImageInfoFromNewImageInfo(
610 ImageInfo &image_info) {
611 if (image_info.header.filetype == llvm::MachO::MH_DYLINKER) {
612 const bool can_create = true;
613 ModuleSP dyld_sp =
614 FindTargetModuleForImageInfo(image_info, can_create, nullptr);
615 if (dyld_sp.get()) {
616 Target &target = m_process->GetTarget();
617 target.GetImages().AppendIfNeeded(dyld_sp);
618 UpdateImageLoadAddress(dyld_sp.get(), image_info);
619 SetDYLDModule(dyld_sp);
620 }
621 }
622 }
623
SetDYLDModule(lldb::ModuleSP & dyld_module_sp)624 void DynamicLoaderDarwin::SetDYLDModule(lldb::ModuleSP &dyld_module_sp) {
625 m_dyld_module_wp = dyld_module_sp;
626 }
627
GetDYLDModule()628 ModuleSP DynamicLoaderDarwin::GetDYLDModule() {
629 ModuleSP dyld_sp(m_dyld_module_wp.lock());
630 return dyld_sp;
631 }
632
ClearDYLDModule()633 void DynamicLoaderDarwin::ClearDYLDModule() { m_dyld_module_wp.reset(); }
634
AddModulesUsingImageInfos(ImageInfo::collection & image_infos)635 bool DynamicLoaderDarwin::AddModulesUsingImageInfos(
636 ImageInfo::collection &image_infos) {
637 std::lock_guard<std::recursive_mutex> guard(m_mutex);
638 // Now add these images to the main list.
639 ModuleList loaded_module_list;
640 Log *log = GetLog(LLDBLog::DynamicLoader);
641 Target &target = m_process->GetTarget();
642 ModuleList &target_images = target.GetImages();
643
644 for (uint32_t idx = 0; idx < image_infos.size(); ++idx) {
645 if (log) {
646 LLDB_LOGF(log, "Adding new image at address=0x%16.16" PRIx64 ".",
647 image_infos[idx].address);
648 image_infos[idx].PutToLog(log);
649 }
650
651 m_dyld_image_infos.push_back(image_infos[idx]);
652
653 ModuleSP image_module_sp(
654 FindTargetModuleForImageInfo(image_infos[idx], true, nullptr));
655
656 if (image_module_sp) {
657 ObjectFile *objfile = image_module_sp->GetObjectFile();
658 if (objfile) {
659 SectionList *sections = objfile->GetSectionList();
660 if (sections) {
661 ConstString commpage_dbstr("__commpage");
662 Section *commpage_section =
663 sections->FindSectionByName(commpage_dbstr).get();
664 if (commpage_section) {
665 ModuleSpec module_spec(objfile->GetFileSpec(),
666 image_infos[idx].GetArchitecture());
667 module_spec.GetObjectName() = commpage_dbstr;
668 ModuleSP commpage_image_module_sp(
669 target_images.FindFirstModule(module_spec));
670 if (!commpage_image_module_sp) {
671 module_spec.SetObjectOffset(objfile->GetFileOffset() +
672 commpage_section->GetFileOffset());
673 module_spec.SetObjectSize(objfile->GetByteSize());
674 commpage_image_module_sp = target.GetOrCreateModule(module_spec,
675 true /* notify */);
676 if (!commpage_image_module_sp ||
677 commpage_image_module_sp->GetObjectFile() == nullptr) {
678 commpage_image_module_sp = m_process->ReadModuleFromMemory(
679 image_infos[idx].file_spec, image_infos[idx].address);
680 // Always load a memory image right away in the target in case
681 // we end up trying to read the symbol table from memory... The
682 // __LINKEDIT will need to be mapped so we can figure out where
683 // the symbol table bits are...
684 bool changed = false;
685 UpdateImageLoadAddress(commpage_image_module_sp.get(),
686 image_infos[idx]);
687 target.GetImages().Append(commpage_image_module_sp);
688 if (changed) {
689 image_infos[idx].load_stop_id = m_process->GetStopID();
690 loaded_module_list.AppendIfNeeded(commpage_image_module_sp);
691 }
692 }
693 }
694 }
695 }
696 }
697
698 // UpdateImageLoadAddress will return true if any segments change load
699 // address. We need to check this so we don't mention that all loaded
700 // shared libraries are newly loaded each time we hit out dyld breakpoint
701 // since dyld will list all shared libraries each time.
702 if (UpdateImageLoadAddress(image_module_sp.get(), image_infos[idx])) {
703 target_images.AppendIfNeeded(image_module_sp);
704 loaded_module_list.AppendIfNeeded(image_module_sp);
705 }
706
707 // To support macCatalyst and legacy iOS simulator,
708 // update the module's platform with the DYLD info.
709 ArchSpec dyld_spec = image_infos[idx].GetArchitecture();
710 auto &dyld_triple = dyld_spec.GetTriple();
711 if ((dyld_triple.getEnvironment() == llvm::Triple::MacABI &&
712 dyld_triple.getOS() == llvm::Triple::IOS) ||
713 (dyld_triple.getEnvironment() == llvm::Triple::Simulator &&
714 (dyld_triple.getOS() == llvm::Triple::IOS ||
715 dyld_triple.getOS() == llvm::Triple::TvOS ||
716 dyld_triple.getOS() == llvm::Triple::WatchOS)))
717 image_module_sp->MergeArchitecture(dyld_spec);
718 }
719 }
720
721 if (loaded_module_list.GetSize() > 0) {
722 if (log)
723 loaded_module_list.LogUUIDAndPaths(log,
724 "DynamicLoaderDarwin::ModulesDidLoad");
725 m_process->GetTarget().ModulesDidLoad(loaded_module_list);
726 }
727 return true;
728 }
729
730 // On Mac OS X libobjc (the Objective-C runtime) has several critical dispatch
731 // functions written in hand-written assembly, and also have hand-written
732 // unwind information in the eh_frame section. Normally we prefer analyzing
733 // the assembly instructions of a currently executing frame to unwind from that
734 // frame -- but on hand-written functions this profiling can fail. We should
735 // use the eh_frame instructions for these functions all the time.
736 //
737 // As an aside, it would be better if the eh_frame entries had a flag (or were
738 // extensible so they could have an Apple-specific flag) which indicates that
739 // the instructions are asynchronous -- accurate at every instruction, instead
740 // of our normal default assumption that they are not.
741
AlwaysRelyOnEHUnwindInfo(SymbolContext & sym_ctx)742 bool DynamicLoaderDarwin::AlwaysRelyOnEHUnwindInfo(SymbolContext &sym_ctx) {
743 ModuleSP module_sp;
744 if (sym_ctx.symbol) {
745 module_sp = sym_ctx.symbol->GetAddressRef().GetModule();
746 }
747 if (module_sp.get() == nullptr && sym_ctx.function) {
748 module_sp =
749 sym_ctx.function->GetAddressRange().GetBaseAddress().GetModule();
750 }
751 if (module_sp.get() == nullptr)
752 return false;
753
754 ObjCLanguageRuntime *objc_runtime = ObjCLanguageRuntime::Get(*m_process);
755 return objc_runtime != nullptr &&
756 objc_runtime->IsModuleObjCLibrary(module_sp);
757 }
758
759 // Dump a Segment to the file handle provided.
PutToLog(Log * log,lldb::addr_t slide) const760 void DynamicLoaderDarwin::Segment::PutToLog(Log *log,
761 lldb::addr_t slide) const {
762 if (log) {
763 if (slide == 0)
764 LLDB_LOGF(log, "\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ")",
765 name.AsCString(""), vmaddr + slide, vmaddr + slide + vmsize);
766 else
767 LLDB_LOGF(log,
768 "\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64
769 ") slide = 0x%" PRIx64,
770 name.AsCString(""), vmaddr + slide, vmaddr + slide + vmsize,
771 slide);
772 }
773 }
774
GetArchitecture() const775 lldb_private::ArchSpec DynamicLoaderDarwin::ImageInfo::GetArchitecture() const {
776 // Update the module's platform with the DYLD info.
777 lldb_private::ArchSpec arch_spec(lldb_private::eArchTypeMachO, header.cputype,
778 header.cpusubtype);
779 if (os_env == llvm::Triple::MacABI && os_type == llvm::Triple::IOS) {
780 llvm::Triple triple(llvm::Twine(arch_spec.GetArchitectureName()) +
781 "-apple-ios" + min_version_os_sdk + "-macabi");
782 ArchSpec maccatalyst_spec(triple);
783 if (arch_spec.IsCompatibleMatch(maccatalyst_spec))
784 arch_spec.MergeFrom(maccatalyst_spec);
785 }
786 if (os_env == llvm::Triple::Simulator &&
787 (os_type == llvm::Triple::IOS || os_type == llvm::Triple::TvOS ||
788 os_type == llvm::Triple::WatchOS)) {
789 llvm::Triple triple(llvm::Twine(arch_spec.GetArchitectureName()) +
790 "-apple-" + llvm::Triple::getOSTypeName(os_type) +
791 min_version_os_sdk + "-simulator");
792 ArchSpec sim_spec(triple);
793 if (arch_spec.IsCompatibleMatch(sim_spec))
794 arch_spec.MergeFrom(sim_spec);
795 }
796 return arch_spec;
797 }
798
799 const DynamicLoaderDarwin::Segment *
FindSegment(ConstString name) const800 DynamicLoaderDarwin::ImageInfo::FindSegment(ConstString name) const {
801 const size_t num_segments = segments.size();
802 for (size_t i = 0; i < num_segments; ++i) {
803 if (segments[i].name == name)
804 return &segments[i];
805 }
806 return nullptr;
807 }
808
809 // Dump an image info structure to the file handle provided.
PutToLog(Log * log) const810 void DynamicLoaderDarwin::ImageInfo::PutToLog(Log *log) const {
811 if (!log)
812 return;
813 if (address == LLDB_INVALID_ADDRESS) {
814 LLDB_LOG(log, "modtime={0:x+8} uuid={1} path='{2}' (UNLOADED)", mod_date,
815 uuid.GetAsString(), file_spec.GetPath());
816 } else {
817 LLDB_LOG(log, "address={0:x+16} modtime={1:x+8} uuid={2} path='{3}'",
818 address, mod_date, uuid.GetAsString(), file_spec.GetPath());
819 for (uint32_t i = 0; i < segments.size(); ++i)
820 segments[i].PutToLog(log, slide);
821 }
822 }
823
PrivateInitialize(Process * process)824 void DynamicLoaderDarwin::PrivateInitialize(Process *process) {
825 DEBUG_PRINTF("DynamicLoaderDarwin::%s() process state = %s\n", __FUNCTION__,
826 StateAsCString(m_process->GetState()));
827 Clear(true);
828 m_process = process;
829 m_process->GetTarget().ClearAllLoadedSections();
830 }
831
832 // Member function that gets called when the process state changes.
PrivateProcessStateChanged(Process * process,StateType state)833 void DynamicLoaderDarwin::PrivateProcessStateChanged(Process *process,
834 StateType state) {
835 DEBUG_PRINTF("DynamicLoaderDarwin::%s(%s)\n", __FUNCTION__,
836 StateAsCString(state));
837 switch (state) {
838 case eStateConnected:
839 case eStateAttaching:
840 case eStateLaunching:
841 case eStateInvalid:
842 case eStateUnloaded:
843 case eStateExited:
844 case eStateDetached:
845 Clear(false);
846 break;
847
848 case eStateStopped:
849 // Keep trying find dyld and set our notification breakpoint each time we
850 // stop until we succeed
851 if (!DidSetNotificationBreakpoint() && m_process->IsAlive()) {
852 if (NeedToDoInitialImageFetch())
853 DoInitialImageFetch();
854
855 SetNotificationBreakpoint();
856 }
857 break;
858
859 case eStateRunning:
860 case eStateStepping:
861 case eStateCrashed:
862 case eStateSuspended:
863 break;
864 }
865 }
866
867 ThreadPlanSP
GetStepThroughTrampolinePlan(Thread & thread,bool stop_others)868 DynamicLoaderDarwin::GetStepThroughTrampolinePlan(Thread &thread,
869 bool stop_others) {
870 ThreadPlanSP thread_plan_sp;
871 StackFrame *current_frame = thread.GetStackFrameAtIndex(0).get();
872 const SymbolContext ¤t_context =
873 current_frame->GetSymbolContext(eSymbolContextSymbol);
874 Symbol *current_symbol = current_context.symbol;
875 Log *log = GetLog(LLDBLog::Step);
876 TargetSP target_sp(thread.CalculateTarget());
877
878 if (current_symbol != nullptr) {
879 std::vector<Address> addresses;
880
881 if (current_symbol->IsTrampoline()) {
882 ConstString trampoline_name =
883 current_symbol->GetMangled().GetName(Mangled::ePreferMangled);
884
885 if (trampoline_name) {
886 const ModuleList &images = target_sp->GetImages();
887
888 SymbolContextList code_symbols;
889 images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeCode,
890 code_symbols);
891 size_t num_code_symbols = code_symbols.GetSize();
892
893 if (num_code_symbols > 0) {
894 for (uint32_t i = 0; i < num_code_symbols; i++) {
895 SymbolContext context;
896 AddressRange addr_range;
897 if (code_symbols.GetContextAtIndex(i, context)) {
898 context.GetAddressRange(eSymbolContextEverything, 0, false,
899 addr_range);
900 addresses.push_back(addr_range.GetBaseAddress());
901 if (log) {
902 addr_t load_addr =
903 addr_range.GetBaseAddress().GetLoadAddress(target_sp.get());
904
905 LLDB_LOGF(log,
906 "Found a trampoline target symbol at 0x%" PRIx64 ".",
907 load_addr);
908 }
909 }
910 }
911 }
912
913 SymbolContextList reexported_symbols;
914 images.FindSymbolsWithNameAndType(
915 trampoline_name, eSymbolTypeReExported, reexported_symbols);
916 size_t num_reexported_symbols = reexported_symbols.GetSize();
917 if (num_reexported_symbols > 0) {
918 for (uint32_t i = 0; i < num_reexported_symbols; i++) {
919 SymbolContext context;
920 if (reexported_symbols.GetContextAtIndex(i, context)) {
921 if (context.symbol) {
922 Symbol *actual_symbol =
923 context.symbol->ResolveReExportedSymbol(*target_sp.get());
924 if (actual_symbol) {
925 const Address actual_symbol_addr =
926 actual_symbol->GetAddress();
927 if (actual_symbol_addr.IsValid()) {
928 addresses.push_back(actual_symbol_addr);
929 if (log) {
930 lldb::addr_t load_addr =
931 actual_symbol_addr.GetLoadAddress(target_sp.get());
932 LLDB_LOGF(
933 log,
934 "Found a re-exported symbol: %s at 0x%" PRIx64 ".",
935 actual_symbol->GetName().GetCString(), load_addr);
936 }
937 }
938 }
939 }
940 }
941 }
942 }
943
944 SymbolContextList indirect_symbols;
945 images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeResolver,
946 indirect_symbols);
947 size_t num_indirect_symbols = indirect_symbols.GetSize();
948 if (num_indirect_symbols > 0) {
949 for (uint32_t i = 0; i < num_indirect_symbols; i++) {
950 SymbolContext context;
951 AddressRange addr_range;
952 if (indirect_symbols.GetContextAtIndex(i, context)) {
953 context.GetAddressRange(eSymbolContextEverything, 0, false,
954 addr_range);
955 addresses.push_back(addr_range.GetBaseAddress());
956 if (log) {
957 addr_t load_addr =
958 addr_range.GetBaseAddress().GetLoadAddress(target_sp.get());
959
960 LLDB_LOGF(log,
961 "Found an indirect target symbol at 0x%" PRIx64 ".",
962 load_addr);
963 }
964 }
965 }
966 }
967 }
968 } else if (current_symbol->GetType() == eSymbolTypeReExported) {
969 // I am not sure we could ever end up stopped AT a re-exported symbol.
970 // But just in case:
971
972 const Symbol *actual_symbol =
973 current_symbol->ResolveReExportedSymbol(*(target_sp.get()));
974 if (actual_symbol) {
975 Address target_addr(actual_symbol->GetAddress());
976 if (target_addr.IsValid()) {
977 LLDB_LOGF(
978 log,
979 "Found a re-exported symbol: %s pointing to: %s at 0x%" PRIx64
980 ".",
981 current_symbol->GetName().GetCString(),
982 actual_symbol->GetName().GetCString(),
983 target_addr.GetLoadAddress(target_sp.get()));
984 addresses.push_back(target_addr.GetLoadAddress(target_sp.get()));
985 }
986 }
987 }
988
989 if (addresses.size() > 0) {
990 // First check whether any of the addresses point to Indirect symbols,
991 // and if they do, resolve them:
992 std::vector<lldb::addr_t> load_addrs;
993 for (Address address : addresses) {
994 Symbol *symbol = address.CalculateSymbolContextSymbol();
995 if (symbol && symbol->IsIndirect()) {
996 Status error;
997 Address symbol_address = symbol->GetAddress();
998 addr_t resolved_addr = thread.GetProcess()->ResolveIndirectFunction(
999 &symbol_address, error);
1000 if (error.Success()) {
1001 load_addrs.push_back(resolved_addr);
1002 LLDB_LOGF(log,
1003 "ResolveIndirectFunction found resolved target for "
1004 "%s at 0x%" PRIx64 ".",
1005 symbol->GetName().GetCString(), resolved_addr);
1006 }
1007 } else {
1008 load_addrs.push_back(address.GetLoadAddress(target_sp.get()));
1009 }
1010 }
1011 thread_plan_sp = std::make_shared<ThreadPlanRunToAddress>(
1012 thread, load_addrs, stop_others);
1013 }
1014 } else {
1015 LLDB_LOGF(log, "Could not find symbol for step through.");
1016 }
1017
1018 return thread_plan_sp;
1019 }
1020
FindEquivalentSymbols(lldb_private::Symbol * original_symbol,lldb_private::ModuleList & images,lldb_private::SymbolContextList & equivalent_symbols)1021 void DynamicLoaderDarwin::FindEquivalentSymbols(
1022 lldb_private::Symbol *original_symbol, lldb_private::ModuleList &images,
1023 lldb_private::SymbolContextList &equivalent_symbols) {
1024 ConstString trampoline_name =
1025 original_symbol->GetMangled().GetName(Mangled::ePreferMangled);
1026 if (!trampoline_name)
1027 return;
1028
1029 static const char *resolver_name_regex = "(_gc|_non_gc|\\$[A-Za-z0-9\\$]+)$";
1030 std::string equivalent_regex_buf("^");
1031 equivalent_regex_buf.append(trampoline_name.GetCString());
1032 equivalent_regex_buf.append(resolver_name_regex);
1033
1034 RegularExpression equivalent_name_regex(equivalent_regex_buf);
1035 images.FindSymbolsMatchingRegExAndType(equivalent_name_regex, eSymbolTypeCode,
1036 equivalent_symbols);
1037
1038 }
1039
GetPThreadLibraryModule()1040 lldb::ModuleSP DynamicLoaderDarwin::GetPThreadLibraryModule() {
1041 ModuleSP module_sp = m_libpthread_module_wp.lock();
1042 if (!module_sp) {
1043 SymbolContextList sc_list;
1044 ModuleSpec module_spec;
1045 module_spec.GetFileSpec().SetFilename("libsystem_pthread.dylib");
1046 ModuleList module_list;
1047 m_process->GetTarget().GetImages().FindModules(module_spec, module_list);
1048 if (!module_list.IsEmpty()) {
1049 if (module_list.GetSize() == 1) {
1050 module_sp = module_list.GetModuleAtIndex(0);
1051 if (module_sp)
1052 m_libpthread_module_wp = module_sp;
1053 }
1054 }
1055 }
1056 return module_sp;
1057 }
1058
GetPthreadSetSpecificAddress()1059 Address DynamicLoaderDarwin::GetPthreadSetSpecificAddress() {
1060 if (!m_pthread_getspecific_addr.IsValid()) {
1061 ModuleSP module_sp = GetPThreadLibraryModule();
1062 if (module_sp) {
1063 lldb_private::SymbolContextList sc_list;
1064 module_sp->FindSymbolsWithNameAndType(ConstString("pthread_getspecific"),
1065 eSymbolTypeCode, sc_list);
1066 SymbolContext sc;
1067 if (sc_list.GetContextAtIndex(0, sc)) {
1068 if (sc.symbol)
1069 m_pthread_getspecific_addr = sc.symbol->GetAddress();
1070 }
1071 }
1072 }
1073 return m_pthread_getspecific_addr;
1074 }
1075
1076 lldb::addr_t
GetThreadLocalData(const lldb::ModuleSP module_sp,const lldb::ThreadSP thread_sp,lldb::addr_t tls_file_addr)1077 DynamicLoaderDarwin::GetThreadLocalData(const lldb::ModuleSP module_sp,
1078 const lldb::ThreadSP thread_sp,
1079 lldb::addr_t tls_file_addr) {
1080 if (!thread_sp || !module_sp)
1081 return LLDB_INVALID_ADDRESS;
1082
1083 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1084
1085 const uint32_t addr_size = m_process->GetAddressByteSize();
1086 uint8_t buf[sizeof(lldb::addr_t) * 3];
1087
1088 lldb_private::Address tls_addr;
1089 if (module_sp->ResolveFileAddress(tls_file_addr, tls_addr)) {
1090 Status error;
1091 const size_t tsl_data_size = addr_size * 3;
1092 Target &target = m_process->GetTarget();
1093 if (target.ReadMemory(tls_addr, buf, tsl_data_size, error, true) ==
1094 tsl_data_size) {
1095 const ByteOrder byte_order = m_process->GetByteOrder();
1096 DataExtractor data(buf, sizeof(buf), byte_order, addr_size);
1097 lldb::offset_t offset = addr_size; // Skip the first pointer
1098 const lldb::addr_t pthread_key = data.GetAddress(&offset);
1099 const lldb::addr_t tls_offset = data.GetAddress(&offset);
1100 if (pthread_key != 0) {
1101 // First check to see if we have already figured out the location of
1102 // TLS data for the pthread_key on a specific thread yet. If we have we
1103 // can re-use it since its location will not change unless the process
1104 // execs.
1105 const tid_t tid = thread_sp->GetID();
1106 auto tid_pos = m_tid_to_tls_map.find(tid);
1107 if (tid_pos != m_tid_to_tls_map.end()) {
1108 auto tls_pos = tid_pos->second.find(pthread_key);
1109 if (tls_pos != tid_pos->second.end()) {
1110 return tls_pos->second + tls_offset;
1111 }
1112 }
1113 StackFrameSP frame_sp = thread_sp->GetStackFrameAtIndex(0);
1114 if (frame_sp) {
1115 TypeSystemClangSP scratch_ts_sp =
1116 ScratchTypeSystemClang::GetForTarget(target);
1117
1118 if (!scratch_ts_sp)
1119 return LLDB_INVALID_ADDRESS;
1120
1121 CompilerType clang_void_ptr_type =
1122 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
1123 Address pthread_getspecific_addr = GetPthreadSetSpecificAddress();
1124 if (pthread_getspecific_addr.IsValid()) {
1125 EvaluateExpressionOptions options;
1126
1127 lldb::ThreadPlanSP thread_plan_sp(new ThreadPlanCallFunction(
1128 *thread_sp, pthread_getspecific_addr, clang_void_ptr_type,
1129 llvm::ArrayRef<lldb::addr_t>(pthread_key), options));
1130
1131 DiagnosticManager execution_errors;
1132 ExecutionContext exe_ctx(thread_sp);
1133 lldb::ExpressionResults results = m_process->RunThreadPlan(
1134 exe_ctx, thread_plan_sp, options, execution_errors);
1135
1136 if (results == lldb::eExpressionCompleted) {
1137 lldb::ValueObjectSP result_valobj_sp =
1138 thread_plan_sp->GetReturnValueObject();
1139 if (result_valobj_sp) {
1140 const lldb::addr_t pthread_key_data =
1141 result_valobj_sp->GetValueAsUnsigned(0);
1142 if (pthread_key_data) {
1143 m_tid_to_tls_map[tid].insert(
1144 std::make_pair(pthread_key, pthread_key_data));
1145 return pthread_key_data + tls_offset;
1146 }
1147 }
1148 }
1149 }
1150 }
1151 }
1152 }
1153 }
1154 return LLDB_INVALID_ADDRESS;
1155 }
1156
UseDYLDSPI(Process * process)1157 bool DynamicLoaderDarwin::UseDYLDSPI(Process *process) {
1158 Log *log = GetLog(LLDBLog::DynamicLoader);
1159 bool use_new_spi_interface = false;
1160
1161 llvm::VersionTuple version = process->GetHostOSVersion();
1162 if (!version.empty()) {
1163 const llvm::Triple::OSType os_type =
1164 process->GetTarget().GetArchitecture().GetTriple().getOS();
1165
1166 // macOS 10.12 and newer
1167 if (os_type == llvm::Triple::MacOSX &&
1168 version >= llvm::VersionTuple(10, 12))
1169 use_new_spi_interface = true;
1170
1171 // iOS 10 and newer
1172 if (os_type == llvm::Triple::IOS && version >= llvm::VersionTuple(10))
1173 use_new_spi_interface = true;
1174
1175 // tvOS 10 and newer
1176 if (os_type == llvm::Triple::TvOS && version >= llvm::VersionTuple(10))
1177 use_new_spi_interface = true;
1178
1179 // watchOS 3 and newer
1180 if (os_type == llvm::Triple::WatchOS && version >= llvm::VersionTuple(3))
1181 use_new_spi_interface = true;
1182
1183 // NEED_BRIDGEOS_TRIPLE // Any BridgeOS
1184 // NEED_BRIDGEOS_TRIPLE if (os_type == llvm::Triple::BridgeOS)
1185 // NEED_BRIDGEOS_TRIPLE use_new_spi_interface = true;
1186 }
1187
1188 if (log) {
1189 if (use_new_spi_interface)
1190 LLDB_LOGF(
1191 log, "DynamicLoaderDarwin::UseDYLDSPI: Use new DynamicLoader plugin");
1192 else
1193 LLDB_LOGF(
1194 log, "DynamicLoaderDarwin::UseDYLDSPI: Use old DynamicLoader plugin");
1195 }
1196 return use_new_spi_interface;
1197 }
1198