LLDB mainline
DynamicLoaderDarwin.cpp
Go to the documentation of this file.
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
10
12#include "lldb/Core/Debugger.h"
13#include "lldb/Core/Module.h"
16#include "lldb/Core/Section.h"
19#include "lldb/Host/HostInfo.h"
22#include "lldb/Target/ABI.h"
25#include "lldb/Target/Target.h"
26#include "lldb/Target/Thread.h"
33#include "lldb/Utility/Log.h"
34#include "lldb/Utility/State.h"
35#include "llvm/Support/ThreadPool.h"
36
39
40//#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN
41#ifdef ENABLE_DEBUG_PRINTF
42#include <cstdio>
43#define DEBUG_PRINTF(fmt, ...) printf(fmt, ##__VA_ARGS__)
44#else
45#define DEBUG_PRINTF(fmt, ...)
46#endif
47
48#include <memory>
49
50using namespace lldb;
51using namespace lldb_private;
52
53// Constructor
58
59// Destructor
61
62/// Called after attaching a process.
63///
64/// Allow DynamicLoader plug-ins to execute some code after
65/// attaching to a process.
71
72/// Called after attaching a process.
73///
74/// Allow DynamicLoader plug-ins to execute some code after
75/// attaching to a process.
81
82// Clear out the state of this class.
83void DynamicLoaderDarwin::Clear(bool clear_process) {
84 std::lock_guard<std::recursive_mutex> guard(m_mutex);
85 if (clear_process)
86 m_process = nullptr;
87 m_dyld_image_infos.clear();
89 m_dyld.Clear(false);
90}
91
93 const ImageInfo &image_info, bool can_create, bool *did_create_ptr) {
94 if (did_create_ptr)
95 *did_create_ptr = false;
96
97 Target &target = m_process->GetTarget();
98 const ModuleList &target_images = target.GetImages();
99 ModuleSpec module_spec(image_info.file_spec);
100 module_spec.GetUUID() = image_info.uuid;
101
102 // macCatalyst support: Request matching os/environment.
103 {
104 auto &target_triple = target.GetArchitecture().GetTriple();
105 if (target_triple.getOS() == llvm::Triple::IOS &&
106 target_triple.getEnvironment() == llvm::Triple::MacABI) {
107 // Request the macCatalyst variant of frameworks that have both
108 // a PLATFORM_MACOS and a PLATFORM_MACCATALYST load command.
109 module_spec.GetArchitecture() = ArchSpec(target_triple);
110 }
111 }
112
113 ModuleSP module_sp(target_images.FindFirstModule(module_spec));
114
115 if (module_sp && !module_spec.GetUUID().IsValid() &&
116 !module_sp->GetUUID().IsValid()) {
117 // No UUID, we must rely upon the cached module modification time and the
118 // modification time of the file on disk
119 if (module_sp->GetModificationTime() !=
120 FileSystem::Instance().GetModificationTime(module_sp->GetFileSpec()))
121 module_sp.reset();
122 }
123
124 if (module_sp || !can_create)
125 return module_sp;
126
127 // See if we have this binary in the Target or the global Module
128 // cache already.
129 module_sp = target.GetOrCreateModule(module_spec, /*notify=*/false);
130
131 if (!module_sp &&
132 HostInfo::GetArchitecture().IsCompatibleMatch(target.GetArchitecture())) {
133
134 SharedCacheImageInfo image_info;
135
136 // If we have a shared cache filepath and UUID, ask HostInfo
137 // if it can provide the SourceCacheImageInfo for the binary
138 // out of that shared cache. Search by the Module's UUID if
139 // available, else the filepath.
140 addr_t sc_base_addr;
141 UUID sc_uuid;
142 LazyBool using_sc;
143 LazyBool private_sc;
144 FileSpec sc_path;
145 std::optional<uint64_t> size;
148 if (GetSharedCacheInformation(sc_base_addr, sc_uuid, using_sc, private_sc,
149 sc_path, size) &&
150 sc_uuid) {
151 if (module_spec.GetUUID())
152 image_info = HostInfo::GetSharedCacheImageInfo(module_spec.GetUUID(),
153 sc_uuid, sc_mode);
154
155 else
156 image_info = HostInfo::GetSharedCacheImageInfo(
157 module_spec.GetFileSpec().GetPathAsConstString(), sc_uuid, sc_mode);
158 } else {
159 // Fall back to looking lldb's own shared cache by filename
160 image_info = HostInfo::GetSharedCacheImageInfo(
161 module_spec.GetFileSpec().GetPathAsConstString(), sc_mode);
162 }
163
164 // If we found it and it has the correct UUID, let's proceed with
165 // creating a module from the memory contents.
166 if (image_info.GetUUID() &&
167 (!module_spec.GetUUID() ||
168 module_spec.GetUUID() == image_info.GetUUID())) {
169 ModuleSpec shared_cache_spec(module_spec.GetFileSpec(),
170 image_info.GetUUID(),
171 image_info.GetExtractor());
172 module_sp =
173 target.GetOrCreateModule(shared_cache_spec, false /* notify */);
174 }
175 }
176 // We'll call Target::ModulesDidLoad after all the modules have been
177 // added to the target, don't let it be called for every one.
178 if (!module_sp || module_sp->GetObjectFile() == nullptr) {
179 llvm::Expected<ModuleSP> module_sp_or_err = m_process->ReadModuleFromMemory(
180 image_info.file_spec, image_info.address);
181 if (auto err = module_sp_or_err.takeError()) {
183 "Failed to load module from memory: {0}");
184 return {};
185 }
186 module_sp = *module_sp_or_err;
187 }
188
189 if (did_create_ptr)
190 *did_create_ptr = (bool)module_sp;
191
192 return module_sp;
193}
194
196 const std::vector<lldb::addr_t> &solib_addresses) {
197 std::lock_guard<std::recursive_mutex> guard(m_mutex);
198 if (m_process->GetStopID() == m_dyld_image_infos_stop_id)
199 return;
200
202 Target &target = m_process->GetTarget();
203 LLDB_LOGF(log, "Removing %" PRId64 " modules.",
204 (uint64_t)solib_addresses.size());
205
206 ModuleList unloaded_module_list;
207
208 for (addr_t solib_addr : solib_addresses) {
209 Address header;
210 if (header.SetLoadAddress(solib_addr, &target)) {
211 if (header.GetOffset() == 0) {
212 ModuleSP module_to_remove(header.GetModule());
213 if (module_to_remove.get()) {
214 LLDB_LOGF(log, "Removing module at address 0x%" PRIx64, solib_addr);
215 // remove the sections from the Target
216 UnloadSections(module_to_remove);
217 // add this to the list of modules to remove
218 unloaded_module_list.AppendIfNeeded(module_to_remove);
219 // remove the entry from the m_dyld_image_infos
220 ImageInfo::collection::iterator pos, end = m_dyld_image_infos.end();
221 for (pos = m_dyld_image_infos.begin(); pos != end; pos++) {
222 if (solib_addr == (*pos).address) {
223 m_dyld_image_infos.erase(pos);
224 break;
225 }
226 }
227 }
228 }
229 }
230 }
231
232 if (unloaded_module_list.GetSize() > 0) {
233 if (log) {
234 log->PutCString("Unloaded:");
235 unloaded_module_list.LogUUIDAndPaths(
236 log, "DynamicLoaderDarwin::UnloadModules");
237 }
238 m_process->GetTarget().GetImages().Remove(unloaded_module_list);
240 }
241}
242
245 ModuleList unloaded_modules_list;
246
247 Target &target = m_process->GetTarget();
248 const ModuleList &target_modules = target.GetImages();
249 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
250
251 ModuleSP dyld_sp(GetDYLDModule());
252 for (ModuleSP module_sp : target_modules.Modules()) {
253 // Don't remove dyld - else we'll lose our breakpoint notifying us about
254 // libraries being re-loaded...
255 if (module_sp && module_sp != dyld_sp) {
256 UnloadSections(module_sp);
257 unloaded_modules_list.Append(module_sp);
258 }
259 }
260
261 if (unloaded_modules_list.GetSize() != 0) {
262 if (log) {
263 log->PutCString("Unloaded:");
264 unloaded_modules_list.LogUUIDAndPaths(
265 log, "DynamicLoaderDarwin::UnloadAllImages");
266 }
267 target.GetImages().Remove(unloaded_modules_list);
268 m_dyld_image_infos.clear();
270 }
271}
272
273// Update the load addresses for all segments in MODULE using the updated INFO
274// that is passed in.
276 ImageInfo &info) {
277 bool changed = false;
279 if (module) {
280 ObjectFile *image_object_file = module->GetObjectFile();
281 if (image_object_file) {
282 SectionList *section_list = image_object_file->GetSectionList();
283 if (section_list) {
284 std::vector<uint32_t> inaccessible_segment_indexes;
285 // We now know the slide amount, so go through all sections and update
286 // the load addresses with the correct values.
287 const size_t num_segments = info.segments.size();
288 for (size_t i = 0; i < num_segments; ++i) {
289 // Only load a segment if it has protections. Things like __PAGEZERO
290 // don't have any protections, and they shouldn't be slid
291 SectionSP section_sp(
292 section_list->FindSectionByName(info.segments[i].name));
293
294 if (info.segments[i].maxprot == 0) {
295 inaccessible_segment_indexes.push_back(i);
296 } else {
297 const addr_t new_section_load_addr =
298 info.segments[i].vmaddr + info.slide;
299 static ConstString g_section_name_LINKEDIT("__LINKEDIT");
300
301 if (section_sp) {
302 // __LINKEDIT sections from files in the shared cache can overlap
303 // so check to see what the segment name is and pass "false" so
304 // we don't warn of overlapping "Section" objects, and "true" for
305 // all other sections.
306 const bool warn_multiple =
307 section_sp->GetName() != g_section_name_LINKEDIT;
308
309 // If a segment was eliminated for the in-memory image,
310 // don't map it into lldb's target section load list.
311 if (info.segments[i].vmsize == 0) {
312 LLDB_LOGF(log, "%s: Omitting zero-size segment %s",
314 info.segments[i].name.AsCString(""));
315 continue;
316 }
317
318 if (info.segments[i].vmsize != section_sp->GetByteSize())
319 LLDB_LOGF(log,
320 "%s: In-memory segment size for %s is 0x%" PRIx64
321 " but file segment size is 0x%" PRIx64,
323 info.segments[i].name.AsCString(""),
324 info.segments[i].vmsize, section_sp->GetByteSize());
325
326 changed = m_process->GetTarget().SetSectionLoadAddress(
327 section_sp, new_section_load_addr, warn_multiple);
328 }
329 }
330 }
331
332 // If the loaded the file (it changed) and we have segments that are
333 // not readable or writeable, add them to the invalid memory region
334 // cache for the process. This will typically only be the __PAGEZERO
335 // segment in the main executable. We might be able to apply this more
336 // generally to more sections that have no protections in the future,
337 // but for now we are going to just do __PAGEZERO.
338 if (changed && !inaccessible_segment_indexes.empty()) {
339 for (uint32_t i = 0; i < inaccessible_segment_indexes.size(); ++i) {
340 const uint32_t seg_idx = inaccessible_segment_indexes[i];
341 SectionSP section_sp(
342 section_list->FindSectionByName(info.segments[seg_idx].name));
343
344 if (section_sp) {
345 static ConstString g_pagezero_section_name("__PAGEZERO");
346 if (g_pagezero_section_name == section_sp->GetName()) {
347 // __PAGEZERO never slides...
348 const lldb::addr_t vmaddr = info.segments[seg_idx].vmaddr;
349 const lldb::addr_t vmsize = info.segments[seg_idx].vmsize;
350 Process::LoadRange pagezero_range(vmaddr, vmsize);
351 m_process->AddInvalidMemoryRegion(pagezero_range);
352 }
353 }
354 }
355 }
356 }
357 }
358 }
359 // We might have an in memory image that was loaded as soon as it was created
360 if (info.load_stop_id == m_process->GetStopID())
361 changed = true;
362 else if (changed) {
363 // Update the stop ID when this library was updated
364 info.load_stop_id = m_process->GetStopID();
365 }
366 return changed;
367}
368
369// Unload the segments in MODULE using the INFO that is passed in.
371 ImageInfo &info) {
372 bool changed = false;
373 if (module) {
374 ObjectFile *image_object_file = module->GetObjectFile();
375 if (image_object_file) {
376 SectionList *section_list = image_object_file->GetSectionList();
377 if (section_list) {
378 const size_t num_segments = info.segments.size();
379 for (size_t i = 0; i < num_segments; ++i) {
380 SectionSP section_sp(
381 section_list->FindSectionByName(info.segments[i].name));
382 if (section_sp) {
383 const addr_t old_section_load_addr =
384 info.segments[i].vmaddr + info.slide;
385 if (m_process->GetTarget().SetSectionUnloaded(
386 section_sp, old_section_load_addr))
387 changed = true;
388 } else {
390 llvm::formatv("unable to find and unload segment named "
391 "'{0}' in '{1}' in macosx dynamic loader plug-in",
392 info.segments[i].name.AsCString("<invalid>"),
393 image_object_file->GetFileSpec().GetPath()));
394 }
395 }
396 }
397 }
398 }
399 return changed;
400}
401
402// Given a JSON dictionary (from debugserver, most likely) of binary images
403// loaded in the inferior process, add the images to the ImageInfo collection.
404
406 StructuredData::ObjectSP image_details,
407 ImageInfo::collection &image_infos) {
408 StructuredData::ObjectSP images_sp =
409 image_details->GetAsDictionary()->GetValueForKey("images");
410 if (images_sp.get() == nullptr)
411 return false;
412
413 image_infos.resize(images_sp->GetAsArray()->GetSize());
414
415 for (size_t i = 0; i < image_infos.size(); i++) {
416 StructuredData::ObjectSP image_sp =
417 images_sp->GetAsArray()->GetItemAtIndex(i);
418 if (image_sp.get() == nullptr || image_sp->GetAsDictionary() == nullptr)
419 return false;
420 StructuredData::Dictionary *image = image_sp->GetAsDictionary();
421 // clang-format off
422 if (!image->HasKey("load_address") ||
423 !image->HasKey("pathname") ||
424 !image->HasKey("mach_header") ||
425 image->GetValueForKey("mach_header")->GetAsDictionary() == nullptr ||
426 !image->HasKey("segments") ||
427 image->GetValueForKey("segments")->GetAsArray() == nullptr ||
428 !image->HasKey("uuid")) {
429 return false;
430 }
431 // clang-format on
432 image_infos[i].address =
433 image->GetValueForKey("load_address")->GetUnsignedIntegerValue();
434 image_infos[i].file_spec.SetFile(
435 image->GetValueForKey("pathname")->GetAsString()->GetValue(),
436 FileSpec::Style::native);
437
439 image->GetValueForKey("mach_header")->GetAsDictionary();
440 image_infos[i].header.magic =
441 mh->GetValueForKey("magic")->GetUnsignedIntegerValue();
442 image_infos[i].header.cputype =
443 mh->GetValueForKey("cputype")->GetUnsignedIntegerValue();
444 image_infos[i].header.cpusubtype =
445 mh->GetValueForKey("cpusubtype")->GetUnsignedIntegerValue();
446 image_infos[i].header.filetype =
447 mh->GetValueForKey("filetype")->GetUnsignedIntegerValue();
448
449 if (image->HasKey("min_version_os_name")) {
450 std::string os_name =
451 std::string(image->GetValueForKey("min_version_os_name")
452 ->GetAsString()
453 ->GetValue());
454 if (os_name == "macosx")
455 image_infos[i].os_type = llvm::Triple::MacOSX;
456 else if (os_name == "ios" || os_name == "iphoneos")
457 image_infos[i].os_type = llvm::Triple::IOS;
458 else if (os_name == "tvos")
459 image_infos[i].os_type = llvm::Triple::TvOS;
460 else if (os_name == "watchos")
461 image_infos[i].os_type = llvm::Triple::WatchOS;
462 else if (os_name == "bridgeos")
463 image_infos[i].os_type = llvm::Triple::BridgeOS;
464 else if (os_name == "driverkit")
465 image_infos[i].os_type = llvm::Triple::DriverKit;
466 else if (os_name == "xros")
467 image_infos[i].os_type = llvm::Triple::XROS;
468 else if (os_name == "maccatalyst") {
469 image_infos[i].os_type = llvm::Triple::IOS;
470 image_infos[i].os_env = llvm::Triple::MacABI;
471 } else if (os_name == "iossimulator") {
472 image_infos[i].os_type = llvm::Triple::IOS;
473 image_infos[i].os_env = llvm::Triple::Simulator;
474 } else if (os_name == "tvossimulator") {
475 image_infos[i].os_type = llvm::Triple::TvOS;
476 image_infos[i].os_env = llvm::Triple::Simulator;
477 } else if (os_name == "watchossimulator") {
478 image_infos[i].os_type = llvm::Triple::WatchOS;
479 image_infos[i].os_env = llvm::Triple::Simulator;
480 } else if (os_name == "xrsimulator") {
481 image_infos[i].os_type = llvm::Triple::XROS;
482 image_infos[i].os_env = llvm::Triple::Simulator;
483 }
484 }
485 if (image->HasKey("min_version_os_sdk")) {
486 image_infos[i].min_version_os_sdk =
487 std::string(image->GetValueForKey("min_version_os_sdk")
488 ->GetAsString()
489 ->GetValue());
490 }
491
492 // Fields that aren't used by DynamicLoaderDarwin so debugserver doesn't
493 // currently send them in the reply.
494
495 if (mh->HasKey("flags"))
496 image_infos[i].header.flags =
497 mh->GetValueForKey("flags")->GetUnsignedIntegerValue();
498 else
499 image_infos[i].header.flags = 0;
500
501 if (mh->HasKey("ncmds"))
502 image_infos[i].header.ncmds =
503 mh->GetValueForKey("ncmds")->GetUnsignedIntegerValue();
504 else
505 image_infos[i].header.ncmds = 0;
506
507 if (mh->HasKey("sizeofcmds"))
508 image_infos[i].header.sizeofcmds =
509 mh->GetValueForKey("sizeofcmds")->GetUnsignedIntegerValue();
510 else
511 image_infos[i].header.sizeofcmds = 0;
512
513 StructuredData::Array *segments =
514 image->GetValueForKey("segments")->GetAsArray();
515 uint32_t segcount = segments->GetSize();
516 for (size_t j = 0; j < segcount; j++) {
519 segments->GetItemAtIndex(j)->GetAsDictionary();
520 segment.name =
521 ConstString(seg->GetValueForKey("name")->GetAsString()->GetValue());
522 segment.vmaddr = seg->GetValueForKey("vmaddr")->GetUnsignedIntegerValue();
523 segment.vmsize = seg->GetValueForKey("vmsize")->GetUnsignedIntegerValue();
524 segment.fileoff =
525 seg->GetValueForKey("fileoff")->GetUnsignedIntegerValue();
526 segment.filesize =
527 seg->GetValueForKey("filesize")->GetUnsignedIntegerValue();
528 segment.maxprot =
529 seg->GetValueForKey("maxprot")->GetUnsignedIntegerValue();
530
531 // Fields that aren't used by DynamicLoaderDarwin so debugserver doesn't
532 // currently send them in the reply.
533
534 if (seg->HasKey("initprot"))
535 segment.initprot =
536 seg->GetValueForKey("initprot")->GetUnsignedIntegerValue();
537 else
538 segment.initprot = 0;
539
540 if (seg->HasKey("flags"))
541 segment.flags = seg->GetValueForKey("flags")->GetUnsignedIntegerValue();
542 else
543 segment.flags = 0;
544
545 if (seg->HasKey("nsects"))
546 segment.nsects =
547 seg->GetValueForKey("nsects")->GetUnsignedIntegerValue();
548 else
549 segment.nsects = 0;
550
551 image_infos[i].segments.push_back(segment);
552 }
553
554 image_infos[i].uuid.SetFromStringRef(
555 image->GetValueForKey("uuid")->GetAsString()->GetValue());
556
557 // All sections listed in the dyld image info structure will all either be
558 // fixed up already, or they will all be off by a single slide amount that
559 // is determined by finding the first segment that is at file offset zero
560 // which also has bytes (a file size that is greater than zero) in the
561 // object file.
562
563 // Determine the slide amount (if any)
564 const size_t num_sections = image_infos[i].segments.size();
565 for (size_t k = 0; k < num_sections; ++k) {
566 // Iterate through the object file sections to find the first section
567 // that starts of file offset zero and that has bytes in the file...
568 if ((image_infos[i].segments[k].fileoff == 0 &&
569 image_infos[i].segments[k].filesize > 0) ||
570 (image_infos[i].segments[k].name == "__TEXT")) {
571 image_infos[i].slide =
572 image_infos[i].address - image_infos[i].segments[k].vmaddr;
573 // We have found the slide amount, so we can exit this for loop.
574 break;
575 }
576 }
577 }
578
579 return true;
580}
581
583 std::vector<std::pair<ImageInfo, ModuleSP>> &images) {
584 uint32_t exe_idx = UINT32_MAX;
585 uint32_t dyld_idx = UINT32_MAX;
586 Target &target = m_process->GetTarget();
588 ConstString g_dyld_sim_filename("dyld_sim");
589
590 ArchSpec target_arch = target.GetArchitecture();
591 const size_t images_size = images.size();
592 for (size_t i = 0; i < images_size; i++) {
593 const auto &image_info = images[i].first;
594 if (image_info.header.filetype == llvm::MachO::MH_DYLINKER) {
595 // In a "simulator" process we will have two dyld modules --
596 // a "dyld" that we want to keep track of, and a "dyld_sim" which
597 // we don't need to keep track of here. dyld_sim will have a non-macosx
598 // OS.
599 if (target_arch.GetTriple().getEnvironment() == llvm::Triple::Simulator &&
600 image_info.os_type != llvm::Triple::OSType::MacOSX) {
601 continue;
602 }
603
604 dyld_idx = i;
605 }
606 if (image_info.header.filetype == llvm::MachO::MH_EXECUTE) {
607 exe_idx = i;
608 }
609 }
610
611 // Set the target executable if we haven't found one so far.
612 if (exe_idx != UINT32_MAX && !target.GetExecutableModule()) {
613 ModuleSP exe_module_sp = images[exe_idx].second;
614 if (exe_module_sp) {
615 LLDB_LOGF(log, "Found executable module: %s",
616 exe_module_sp->GetFileSpec().GetPath().c_str());
617 target.GetImages().AppendIfNeeded(exe_module_sp);
618 UpdateImageLoadAddress(exe_module_sp.get(), images[exe_idx].first);
619 if (exe_module_sp.get() != target.GetExecutableModulePointer())
620 target.SetExecutableModule(exe_module_sp, eLoadDependentsNo);
621
622 // Update the target executable's arch if necessary.
623 auto exe_triple = exe_module_sp->GetArchitecture().GetTriple();
624 if (target_arch.GetTriple().isArm64e() &&
625 exe_triple.getArch() == llvm::Triple::aarch64 &&
626 !exe_triple.isArm64e()) {
627 // On arm64e-capable Apple platforms, the system libraries are
628 // always arm64e, but applications often are arm64. When a
629 // target is created from a file, LLDB recognizes it as an
630 // arm64 target, but debugserver will still (technically
631 // correct) report the process as being arm64e. For
632 // consistency, set the target to arm64 here, so attaching to
633 // a live process behaves the same as creating a process from
634 // file.
635 auto triple = target_arch.GetTriple();
636 triple.setArchName(exe_triple.getArchName());
637 target_arch.SetTriple(triple);
638 target.SetArchitecture(target_arch, /*set_platform=*/false,
639 /*merge=*/false);
640 }
641 }
642 }
643
644 if (dyld_idx != UINT32_MAX) {
645 ModuleSP dyld_sp = images[dyld_idx].second;
646 if (dyld_sp.get()) {
647 LLDB_LOGF(log, "Found dyld module: %s",
648 dyld_sp->GetFileSpec().GetPath().c_str());
649 target.GetImages().AppendIfNeeded(dyld_sp);
650 UpdateImageLoadAddress(dyld_sp.get(), images[dyld_idx].first);
651 SetDYLDModule(dyld_sp);
652 }
653 }
654}
655
657 ImageInfo &image_info) {
658 if (image_info.header.filetype == llvm::MachO::MH_DYLINKER) {
659 const bool can_create = true;
660 ModuleSP dyld_sp =
661 FindTargetModuleForImageInfo(image_info, can_create, nullptr);
662 if (dyld_sp.get()) {
663 Target &target = m_process->GetTarget();
664 target.GetImages().AppendIfNeeded(dyld_sp);
665 UpdateImageLoadAddress(dyld_sp.get(), image_info);
666 SetDYLDModule(dyld_sp);
667 return true;
668 }
669 }
670 return false;
671}
672
673std::optional<lldb_private::Address> DynamicLoaderDarwin::GetStartAddress() {
675
676 auto log_err = [log](llvm::StringLiteral err_msg) -> std::nullopt_t {
677 LLDB_LOG_VERBOSE(log, "{}", err_msg);
678 return std::nullopt;
679 };
680
681 ModuleSP dyld_sp = GetDYLDModule();
682 if (!dyld_sp)
683 return log_err("Couldn't retrieve DYLD module. Cannot get `start` symbol.");
684
685 const Symbol *symbol =
686 dyld_sp->FindFirstSymbolWithNameAndType(ConstString("_dyld_start"));
687 if (!symbol)
688 return log_err("Cannot find `start` symbol in DYLD module.");
689
690 return symbol->GetAddress();
691}
692
694 m_dyld_module_wp = dyld_module_sp;
695}
696
698 ModuleSP dyld_sp(m_dyld_module_wp.lock());
699 return dyld_sp;
700}
701
703
704std::vector<std::pair<DynamicLoaderDarwin::ImageInfo, ModuleSP>>
706 const ImageInfo::collection &image_infos) {
707 const auto size = image_infos.size();
708 std::vector<std::pair<DynamicLoaderDarwin::ImageInfo, ModuleSP>> images(size);
709 auto LoadImage = [&](size_t i, ImageInfo::collection::const_iterator it) {
710 const auto &image_info = *it;
711 images[i] = std::make_pair(
712 image_info, FindTargetModuleForImageInfo(image_info, true, nullptr));
713 };
714 auto it = image_infos.begin();
715 bool is_parallel_load = m_process->GetTarget().GetParallelModuleLoad();
716 if (is_parallel_load) {
717 llvm::ThreadPoolTaskGroup taskGroup(Debugger::GetThreadPool());
718 for (size_t i = 0; i < size; ++i, ++it) {
719 taskGroup.async(LoadImage, i, it);
720 }
721 taskGroup.wait();
722 } else {
723 for (size_t i = 0; i < size; ++i, ++it) {
724 LoadImage(i, it);
725 }
726 }
727 return images;
728}
729
731 ImageInfo::collection &image_infos) {
732 std::lock_guard<std::recursive_mutex> guard(m_mutex);
733 auto images = PreloadModulesFromImageInfos(image_infos);
734 return AddModulesUsingPreloadedModules(images);
735}
736
738 std::vector<std::pair<ImageInfo, ModuleSP>> &images) {
739 std::lock_guard<std::recursive_mutex> guard(m_mutex);
740 // Now add these images to the main list.
741 ModuleList loaded_module_list;
743 Target &target = m_process->GetTarget();
744 ModuleList &target_images = target.GetImages();
745
746 for (uint32_t idx = 0; idx < images.size(); ++idx) {
747 auto &image_info = images[idx].first;
748 const auto &image_module_sp = images[idx].second;
749 if (log) {
750 LLDB_LOGF(log, "Adding new image at address=0x%16.16" PRIx64 ".",
751 image_info.address);
752 image_info.PutToLog(log);
753 }
754 m_dyld_image_infos.push_back(image_info);
755
756 if (image_module_sp) {
757 ObjectFile *objfile = image_module_sp->GetObjectFile();
758 if (objfile) {
759 SectionList *sections = objfile->GetSectionList();
760 if (sections) {
761 ConstString commpage_dbstr("__commpage");
762 Section *commpage_section =
763 sections->FindSectionByName(commpage_dbstr).get();
764 if (commpage_section) {
765 ModuleSpec module_spec(objfile->GetFileSpec(),
766 image_info.GetArchitecture());
767 module_spec.GetObjectName() = commpage_dbstr;
768 ModuleSP commpage_image_module_sp(
769 target_images.FindFirstModule(module_spec));
770 if (!commpage_image_module_sp) {
771 module_spec.SetObjectOffset(objfile->GetFileOffset() +
772 commpage_section->GetFileOffset());
773 module_spec.SetObjectSize(objfile->GetByteSize());
774 commpage_image_module_sp = target.GetOrCreateModule(module_spec,
775 true /* notify */);
776 if (!commpage_image_module_sp ||
777 commpage_image_module_sp->GetObjectFile() == nullptr) {
778 llvm::Expected<ModuleSP> module_sp_or_err =
779 m_process->ReadModuleFromMemory(image_info.file_spec,
780 image_info.address);
781 if (auto err = module_sp_or_err.takeError()) {
782 LLDB_LOG_ERROR(log, std::move(err),
783 "Failed to read module from memory: {0}");
784 } else {
785 // Always load a memory image right away in the target in case
786 // we end up trying to read the symbol table from memory...
787 // The __LINKEDIT will need to be mapped so we can figure out
788 // where the symbol table bits are...
789 commpage_image_module_sp = *module_sp_or_err;
790 bool changed = false;
791 UpdateImageLoadAddress(commpage_image_module_sp.get(),
792 image_info);
793 target.GetImages().Append(commpage_image_module_sp);
794 if (changed) {
795 image_info.load_stop_id = m_process->GetStopID();
796 loaded_module_list.AppendIfNeeded(commpage_image_module_sp);
797 }
798 }
799 }
800 }
801 }
802 }
803 }
804
805 // UpdateImageLoadAddress will return true if any segments change load
806 // address. We need to check this so we don't mention that all loaded
807 // shared libraries are newly loaded each time we hit out dyld breakpoint
808 // since dyld will list all shared libraries each time.
809 if (UpdateImageLoadAddress(image_module_sp.get(), image_info)) {
810 target_images.AppendIfNeeded(image_module_sp);
811 loaded_module_list.AppendIfNeeded(image_module_sp);
812 }
813
814 // To support macCatalyst and legacy iOS simulator,
815 // update the module's platform with the DYLD info.
816 ArchSpec dyld_spec = image_info.GetArchitecture();
817 auto &dyld_triple = dyld_spec.GetTriple();
818 if ((dyld_triple.getEnvironment() == llvm::Triple::MacABI &&
819 dyld_triple.getOS() == llvm::Triple::IOS) ||
820 (dyld_triple.getEnvironment() == llvm::Triple::Simulator &&
821 (dyld_triple.getOS() == llvm::Triple::IOS ||
822 dyld_triple.getOS() == llvm::Triple::TvOS ||
823 dyld_triple.getOS() == llvm::Triple::WatchOS ||
824 dyld_triple.getOS() == llvm::Triple::XROS)))
825 image_module_sp->MergeArchitecture(dyld_spec);
826 }
827 }
828
829 if (loaded_module_list.GetSize() > 0) {
830 if (log)
831 loaded_module_list.LogUUIDAndPaths(log,
832 "DynamicLoaderDarwin::ModulesDidLoad");
833 m_process->GetTarget().ModulesDidLoad(loaded_module_list);
834 }
835 return true;
836}
837
838// On Mac OS X libobjc (the Objective-C runtime) has several critical dispatch
839// functions written in hand-written assembly, and also have hand-written
840// unwind information in the eh_frame section. Normally we prefer analyzing
841// the assembly instructions of a currently executing frame to unwind from that
842// frame -- but on hand-written functions this profiling can fail. We should
843// use the eh_frame instructions for these functions all the time.
844//
845// As an aside, it would be better if the eh_frame entries had a flag (or were
846// extensible so they could have an Apple-specific flag) which indicates that
847// the instructions are asynchronous -- accurate at every instruction, instead
848// of our normal default assumption that they are not.
849
851 ModuleSP module_sp;
852 if (sym_ctx.symbol) {
853 module_sp = sym_ctx.symbol->GetAddressRef().GetModule();
854 }
855 if (module_sp.get() == nullptr && sym_ctx.function)
856 module_sp = sym_ctx.function->GetAddress().GetModule();
857 if (module_sp.get() == nullptr)
858 return false;
859
861 return objc_runtime != nullptr &&
862 objc_runtime->IsModuleObjCLibrary(module_sp);
863}
864
865// Dump a Segment to the file handle provided.
867 lldb::addr_t slide) const {
868 if (slide == 0)
869 LLDB_LOGF(log, "\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ")",
870 name.AsCString(""), vmaddr + slide, vmaddr + slide + vmsize);
871 else
872 LLDB_LOGF(
873 log,
874 "\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ") slide = 0x%" PRIx64,
875 name.AsCString(""), vmaddr + slide, vmaddr + slide + vmsize, slide);
876}
877
879 // Update the module's platform with the DYLD info.
881 header.cpusubtype);
882 if (os_env == llvm::Triple::MacABI && os_type == llvm::Triple::IOS) {
883 llvm::Triple triple(llvm::Twine(arch_spec.GetArchitectureName()) +
884 "-apple-ios" + min_version_os_sdk + "-macabi");
885 ArchSpec maccatalyst_spec(triple);
886 if (arch_spec.IsCompatibleMatch(maccatalyst_spec))
887 arch_spec.MergeFrom(maccatalyst_spec);
888 }
889 if (os_env == llvm::Triple::Simulator &&
890 (os_type == llvm::Triple::IOS || os_type == llvm::Triple::TvOS ||
891 os_type == llvm::Triple::WatchOS || os_type == llvm::Triple::XROS)) {
892 llvm::Triple triple(llvm::Twine(arch_spec.GetArchitectureName()) +
893 "-apple-" + llvm::Triple::getOSTypeName(os_type) +
894 min_version_os_sdk + "-simulator");
895 ArchSpec sim_spec(triple);
896 if (arch_spec.IsCompatibleMatch(sim_spec))
897 arch_spec.MergeFrom(sim_spec);
898 }
899 return arch_spec;
900}
901
904 const size_t num_segments = segments.size();
905 for (size_t i = 0; i < num_segments; ++i) {
906 if (segments[i].name == name)
907 return &segments[i];
908 }
909 return nullptr;
910}
911
912// Dump an image info structure to the file handle provided.
914 if (!log)
915 return;
917 LLDB_LOG(log, "uuid={} path='{}' (UNLOADED)", uuid.GetAsString(),
918 file_spec.GetPath());
919 } else {
920 LLDB_LOG(log, "address={0:x+16} uuid={1} path='{2}'", address,
921 uuid.GetAsString(), file_spec.GetPath());
922 for (uint32_t i = 0; i < segments.size(); ++i)
923 segments[i].PutToLog(log, slide);
924 }
925}
926
928 DEBUG_PRINTF("DynamicLoaderDarwin::%s() process state = %s\n", __FUNCTION__,
929 StateAsCString(m_process->GetState()));
930 Clear(true);
931 m_process = process;
932}
933
934// Member function that gets called when the process state changes.
936 StateType state) {
937 DEBUG_PRINTF("DynamicLoaderDarwin::%s(%s)\n", __FUNCTION__,
938 StateAsCString(state));
939 switch (state) {
940 case eStateConnected:
941 case eStateAttaching:
942 case eStateLaunching:
943 case eStateInvalid:
944 case eStateUnloaded:
945 case eStateExited:
946 case eStateDetached:
947 Clear(false);
948 break;
949
950 case eStateStopped:
951 // Keep trying find dyld and set our notification breakpoint each time we
952 // stop until we succeed
953 if (!DidSetNotificationBreakpoint() && m_process->IsAlive()) {
956
958 }
959 break;
960
961 case eStateRunning:
962 case eStateStepping:
963 case eStateCrashed:
964 case eStateSuspended:
965 break;
966 }
967}
968
971 bool stop_others) {
972 ThreadPlanSP thread_plan_sp;
973 StackFrame *current_frame = thread.GetStackFrameAtIndex(0).get();
974 const SymbolContext &current_context =
975 current_frame->GetSymbolContext(eSymbolContextSymbol);
976 const Symbol *current_symbol = current_context.symbol;
977 Log *log = GetLog(LLDBLog::Step);
978 TargetSP target_sp(thread.CalculateTarget());
979
980 if (current_symbol != nullptr) {
981 std::vector<Address> addresses;
982
983 ConstString current_name =
984 current_symbol->GetMangled().GetName(Mangled::ePreferMangled);
985 if (current_symbol->IsTrampoline()) {
986
987 if (current_name) {
988 const ModuleList &images = target_sp->GetImages();
989
990 SymbolContextList code_symbols;
991 images.FindSymbolsWithNameAndType(current_name, eSymbolTypeCode,
992 code_symbols);
993 for (const SymbolContext &context : code_symbols) {
994 Address addr = context.GetFunctionOrSymbolAddress();
995 addresses.push_back(addr);
996 if (log) {
997 addr_t load_addr = addr.GetLoadAddress(target_sp.get());
998
999 LLDB_LOGF(log, "Found a trampoline target symbol at 0x%" PRIx64 ".",
1000 load_addr);
1001 }
1002 }
1003
1004 SymbolContextList reexported_symbols;
1006 reexported_symbols);
1007 for (const SymbolContext &context : reexported_symbols) {
1008 if (context.symbol) {
1009 const Symbol *actual_symbol =
1010 context.symbol->ResolveReExportedSymbol(*target_sp.get());
1011 if (actual_symbol) {
1012 const Address actual_symbol_addr = actual_symbol->GetAddress();
1013 if (actual_symbol_addr.IsValid()) {
1014 addresses.push_back(actual_symbol_addr);
1015 if (log) {
1016 lldb::addr_t load_addr =
1017 actual_symbol_addr.GetLoadAddress(target_sp.get());
1018 LLDB_LOGF(log,
1019 "Found a re-exported symbol: %s at 0x%" PRIx64 ".",
1020 actual_symbol->GetName().GetCString(), load_addr);
1021 }
1022 }
1023 }
1024 }
1025 }
1026
1027 SymbolContextList indirect_symbols;
1029 indirect_symbols);
1030
1031 for (const SymbolContext &context : indirect_symbols) {
1032 Address addr = context.GetFunctionOrSymbolAddress();
1033 addresses.push_back(addr);
1034 if (log) {
1035 addr_t load_addr = addr.GetLoadAddress(target_sp.get());
1036
1037 LLDB_LOGF(log, "Found an indirect target symbol at 0x%" PRIx64 ".",
1038 load_addr);
1039 }
1040 }
1041 }
1042 } else if (current_symbol->GetType() == eSymbolTypeReExported) {
1043 // I am not sure we could ever end up stopped AT a re-exported symbol.
1044 // But just in case:
1045
1046 const Symbol *actual_symbol =
1047 current_symbol->ResolveReExportedSymbol(*(target_sp.get()));
1048 if (actual_symbol) {
1049 Address target_addr(actual_symbol->GetAddress());
1050 if (target_addr.IsValid()) {
1051 LLDB_LOGF(
1052 log,
1053 "Found a re-exported symbol: %s pointing to: %s at 0x%" PRIx64
1054 ".",
1055 current_symbol->GetName().GetCString(),
1056 actual_symbol->GetName().GetCString(),
1057 target_addr.GetLoadAddress(target_sp.get()));
1058 addresses.push_back(
1059 Address(target_addr.GetLoadAddress(target_sp.get())));
1060 }
1061 }
1062 }
1063
1064 if (addresses.size() > 0) {
1065 // First check whether any of the addresses point to Indirect symbols,
1066 // and if they do, resolve them:
1067 std::vector<lldb::addr_t> load_addrs;
1068 for (Address address : addresses) {
1069 const Symbol *symbol = address.CalculateSymbolContextSymbol();
1070 if (symbol && symbol->IsIndirect()) {
1071 Status error;
1072 Address symbol_address = symbol->GetAddress();
1073 addr_t resolved_addr = thread.GetProcess()->ResolveIndirectFunction(
1074 &symbol_address, error);
1075 if (error.Success()) {
1076 load_addrs.push_back(resolved_addr);
1077 LLDB_LOGF(log,
1078 "ResolveIndirectFunction found resolved target for "
1079 "%s at 0x%" PRIx64 ".",
1080 symbol->GetName().GetCString(), resolved_addr);
1081 }
1082 } else {
1083 load_addrs.push_back(address.GetLoadAddress(target_sp.get()));
1084 }
1085 }
1086 thread_plan_sp = std::make_shared<ThreadPlanRunToAddress>(
1087 thread, load_addrs, stop_others);
1088 }
1089 // One more case we have to consider is "branch islands". These are regular
1090 // TEXT symbols but their names end in .island plus maybe a .digit suffix.
1091 // They are to allow arm64 code to branch further than the size of the
1092 // address slot allows. We just need to single-instruction step in that
1093 // case.
1094 static const char *g_branch_island_pattern = "\\.island\\.?[0-9]*$";
1095 static RegularExpression g_branch_island_regex(g_branch_island_pattern);
1096
1097 bool is_branch_island = g_branch_island_regex.Execute(current_name);
1098 if (!thread_plan_sp && is_branch_island) {
1099 thread_plan_sp = std::make_shared<ThreadPlanStepInstruction>(
1100 thread,
1101 /* step_over= */ false, /* stop_others */ false, eVoteNoOpinion,
1103 LLDB_LOG(log, "Stepping one instruction over branch island: '{0}'.",
1104 current_name);
1105 }
1106 } else {
1107 LLDB_LOGF(log, "Could not find symbol for step through.");
1108 }
1109
1110 return thread_plan_sp;
1111}
1112
1114 const lldb_private::Symbol *original_symbol,
1116 lldb_private::SymbolContextList &equivalent_symbols) {
1117 ConstString trampoline_name =
1118 original_symbol->GetMangled().GetName(Mangled::ePreferMangled);
1119 if (!trampoline_name)
1120 return;
1121
1122 static const char *resolver_name_regex = "(_gc|_non_gc|\\$[A-Za-z0-9\\$]+)$";
1123 std::string equivalent_regex_buf("^");
1124 equivalent_regex_buf.append(trampoline_name.GetCString());
1125 equivalent_regex_buf.append(resolver_name_regex);
1126
1127 RegularExpression equivalent_name_regex(equivalent_regex_buf);
1128 images.FindSymbolsMatchingRegExAndType(equivalent_name_regex, eSymbolTypeCode,
1129 equivalent_symbols);
1130}
1131
1133 ModuleSP module_sp = m_libpthread_module_wp.lock();
1134 if (!module_sp) {
1135 SymbolContextList sc_list;
1136 ModuleSpec module_spec;
1137 module_spec.GetFileSpec().SetFilename("libsystem_pthread.dylib");
1138 ModuleList module_list;
1139 m_process->GetTarget().GetImages().FindModules(module_spec, module_list);
1140 if (!module_list.IsEmpty()) {
1141 if (module_list.GetSize() == 1) {
1142 module_sp = module_list.GetModuleAtIndex(0);
1143 if (module_sp)
1144 m_libpthread_module_wp = module_sp;
1145 }
1146 }
1147 }
1148 return module_sp;
1149}
1150
1152 if (!m_pthread_getspecific_addr.IsValid()) {
1153 ModuleSP module_sp = GetPThreadLibraryModule();
1154 if (module_sp) {
1156 module_sp->FindSymbolsWithNameAndType(ConstString("pthread_getspecific"),
1157 eSymbolTypeCode, sc_list);
1158 SymbolContext sc;
1159 if (sc_list.GetContextAtIndex(0, sc)) {
1160 if (sc.symbol)
1162 }
1163 }
1164 }
1166}
1167
1170 const lldb::ThreadSP thread_sp,
1171 lldb::addr_t tls_file_addr) {
1172 if (!thread_sp || !module_sp)
1173 return LLDB_INVALID_ADDRESS;
1174
1175 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1176
1177 lldb_private::Address tls_addr;
1178 if (!module_sp->ResolveFileAddress(tls_file_addr, tls_addr))
1179 return LLDB_INVALID_ADDRESS;
1180
1181 Target &target = m_process->GetTarget();
1182 TypeSystemClangSP scratch_ts_sp =
1184 if (!scratch_ts_sp)
1185 return LLDB_INVALID_ADDRESS;
1186
1187 CompilerType clang_void_ptr_type =
1188 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
1189
1190 auto evaluate_tls_address = [this, &thread_sp, &clang_void_ptr_type](
1191 Address func_ptr,
1192 llvm::ArrayRef<addr_t> args) -> addr_t {
1194
1195 lldb::ThreadPlanSP thread_plan_sp(new ThreadPlanCallFunction(
1196 *thread_sp, func_ptr, clang_void_ptr_type, args, options));
1197
1198 DiagnosticManager execution_errors;
1199 ExecutionContext exe_ctx(thread_sp);
1200 lldb::ExpressionResults results = m_process->RunThreadPlan(
1201 exe_ctx, thread_plan_sp, options, execution_errors);
1202
1203 if (results == lldb::eExpressionCompleted) {
1204 if (lldb::ValueObjectSP result_valobj_sp =
1205 thread_plan_sp->GetReturnValueObject()) {
1206 return result_valobj_sp->GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
1207 }
1208 }
1209 return LLDB_INVALID_ADDRESS;
1210 };
1211
1212 // On modern apple platforms, there is a small data structure that looks
1213 // approximately like this:
1214 // struct TLS_Thunk {
1215 // void *(*get_addr)(struct TLS_Thunk *);
1216 // size_t key;
1217 // size_t offset;
1218 // }
1219 //
1220 // The strategy is to take get_addr and call it with the address of the
1221 // containing TLS_Thunk structure.
1222 //
1223 // On older apple platforms, the key is treated as a pthread_key_t and passed
1224 // to pthread_getspecific. The pointer returned from that call is added to
1225 // offset to get the relevant data block.
1226
1227 const uint32_t addr_size = m_process->GetAddressByteSize();
1228 uint8_t buf[sizeof(addr_t) * 3];
1229 Status error;
1230 const size_t tls_data_size = addr_size * 3;
1231 const size_t bytes_read = target.ReadMemory(
1232 tls_addr, buf, tls_data_size, error, /*force_live_memory = */ true);
1233 if (bytes_read != tls_data_size || error.Fail())
1234 return LLDB_INVALID_ADDRESS;
1235
1236 DataExtractor data(buf, sizeof(buf), m_process->GetByteOrder(), addr_size);
1237 lldb::offset_t offset = 0;
1238 const addr_t tls_thunk = data.GetAddress(&offset);
1239 const addr_t key = data.GetAddress(&offset);
1240 const addr_t tls_offset = data.GetAddress(&offset);
1241
1242 if (tls_thunk != 0) {
1243 const addr_t fixed_tls_thunk = m_process->FixCodeAddress(tls_thunk);
1244 Address thunk_load_addr;
1245 if (target.ResolveLoadAddress(fixed_tls_thunk, thunk_load_addr)) {
1246 const addr_t tls_load_addr = tls_addr.GetLoadAddress(&target);
1247 const addr_t tls_data = evaluate_tls_address(
1248 thunk_load_addr, llvm::ArrayRef<addr_t>(tls_load_addr));
1249 if (tls_data != LLDB_INVALID_ADDRESS)
1250 return tls_data;
1251 }
1252 }
1253
1254 if (key != 0) {
1255 // First check to see if we have already figured out the location of
1256 // TLS data for the pthread_key on a specific thread yet. If we have we
1257 // can re-use it since its location will not change unless the process
1258 // execs.
1259 const lldb::tid_t tid = thread_sp->GetID();
1260 auto tid_pos = m_tid_to_tls_map.find(tid);
1261 if (tid_pos != m_tid_to_tls_map.end()) {
1262 auto tls_pos = tid_pos->second.find(key);
1263 if (tls_pos != tid_pos->second.end()) {
1264 return tls_pos->second + tls_offset;
1265 }
1266 }
1267 Address pthread_getspecific_addr = GetPthreadSetSpecificAddress();
1268 if (pthread_getspecific_addr.IsValid()) {
1269 const addr_t tls_data = evaluate_tls_address(pthread_getspecific_addr,
1270 llvm::ArrayRef<addr_t>(key));
1271 if (tls_data != LLDB_INVALID_ADDRESS)
1272 return tls_data + tls_offset;
1273 }
1274 }
1275 return LLDB_INVALID_ADDRESS;
1276}
1277
1280 bool use_new_spi_interface = true;
1281
1282 llvm::VersionTuple version = process->GetHostOSVersion();
1283 if (!version.empty()) {
1284 using namespace llvm;
1285 const Triple::OSType os_type =
1286 process->GetTarget().GetArchitecture().GetTriple().getOS();
1287
1288 auto OlderThan = [os_type, version](llvm::Triple::OSType o,
1289 llvm::VersionTuple v) -> bool {
1290 return os_type == o && version < v;
1291 };
1292
1293 if (OlderThan(Triple::MacOSX, VersionTuple(10, 12)))
1294 use_new_spi_interface = false;
1295
1296 if (OlderThan(Triple::IOS, VersionTuple(10)))
1297 use_new_spi_interface = false;
1298
1299 if (OlderThan(Triple::TvOS, VersionTuple(10)))
1300 use_new_spi_interface = false;
1301
1302 if (OlderThan(Triple::WatchOS, VersionTuple(3)))
1303 use_new_spi_interface = false;
1304
1305 // llvm::Triple::BridgeOS and llvm::Triple::XROS always use the new
1306 // libdyld SPI interface.
1307 } else {
1308 // We could not get an OS version string, we are likely not
1309 // connected to debugserver and the packets to call the libdyld SPI
1310 // will not exist.
1311 use_new_spi_interface = false;
1312 }
1313
1314 // Corefiles cannot use the libdyld SPI to get the inferior's
1315 // binaries, we must find it through metadata or a scan
1316 // of the corefile memory.
1317 if (!process->IsLiveDebugSession())
1318 use_new_spi_interface = false;
1319
1320 if (log) {
1321 if (use_new_spi_interface)
1322 LLDB_LOGF(
1323 log, "DynamicLoaderDarwin::UseDYLDSPI: Use new DynamicLoader plugin");
1324 else
1325 LLDB_LOGF(
1326 log, "DynamicLoaderDarwin::UseDYLDSPI: Use old DynamicLoader plugin");
1327 }
1328 return use_new_spi_interface;
1329}
static llvm::raw_ostream & error(Stream &strm)
#define DEBUG_PRINTF(fmt,...)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:364
#define LLDB_LOGF(log,...)
Definition Log.h:378
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:394
#define LLDB_LOG_VERBOSE(log,...)
Definition Log.h:371
A section + offset based address class.
Definition Address.h:62
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition Address.cpp:301
bool SetLoadAddress(lldb::addr_t load_addr, Target *target, bool allow_section_end=false)
Set the address to represent load_addr.
Definition Address.cpp:1034
lldb::ModuleSP GetModule() const
Get accessor for the module for this address.
Definition Address.cpp:273
lldb::addr_t GetOffset() const
Get the section relative offset value.
Definition Address.h:329
bool IsValid() const
Check if the object state is valid.
Definition Address.h:355
An architecture specification class.
Definition ArchSpec.h:32
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:460
bool SetTriple(const llvm::Triple &triple)
Architecture triple setter.
Definition ArchSpec.cpp:748
void MergeFrom(const ArchSpec &other)
Merges fields from another ArchSpec into this ArchSpec.
Definition ArchSpec.cpp:810
bool IsCompatibleMatch(const ArchSpec &rhs) const
Shorthand for IsMatch(rhs, CompatibleMatch).
Definition ArchSpec.h:512
const char * GetArchitectureName() const
Returns a static string representing the current architecture.
Definition ArchSpec.cpp:557
Generic representation of a type in a programming language.
A uniqued constant string class.
Definition ConstString.h:40
const char * GetCString() const
Get the string value as a C string.
const char * AsCString(const char *value_if_empty) const
Get the string value as a C string.
An data extractor class.
uint64_t GetAddress(lldb::offset_t *offset_ptr) const
Extract an address from *offset_ptr.
static void ReportWarning(std::string message, std::optional< lldb::user_id_t > debugger_id=std::nullopt, std::once_flag *once=nullptr)
Report warning events.
static llvm::ThreadPoolInterface & GetThreadPool()
Shared thread pool. Use only with ThreadPoolTaskGroup.
void PutToLog(lldb_private::Log *log, lldb::addr_t slide) const
lldb::addr_t GetThreadLocalData(const lldb::ModuleSP module, const lldb::ThreadSP thread, lldb::addr_t tls_file_addr) override
Retrieves the per-module TLS block for a given thread.
bool UpdateDYLDImageInfoFromNewImageInfo(ImageInfo &image_info)
bool AlwaysRelyOnEHUnwindInfo(lldb_private::SymbolContext &sym_ctx) override
Ask if the eh_frame information for the given SymbolContext should be relied on even when it's the fi...
virtual bool NeedToDoInitialImageFetch()=0
virtual void DoInitialImageFetch()=0
DynamicLoaderDarwin(lldb_private::Process *process)
void PrivateProcessStateChanged(lldb_private::Process *process, lldb::StateType state)
void DidLaunch() override
Called after attaching a process.
lldb::ModuleSP FindTargetModuleForImageInfo(const ImageInfo &image_info, bool can_create, bool *did_create_ptr)
virtual bool SetNotificationBreakpoint()=0
bool AddModulesUsingImageInfos(ImageInfo::collection &image_infos)
void FindEquivalentSymbols(const lldb_private::Symbol *original_symbol, lldb_private::ModuleList &module_list, lldb_private::SymbolContextList &equivalent_symbols) override
Some dynamic loaders provide features where there are a group of symbols "equivalent to" a given symb...
void DidAttach() override
Called after attaching a process.
lldb::ThreadPlanSP GetStepThroughTrampolinePlan(lldb_private::Thread &thread, bool stop_others) override
Provides a plan to step through the dynamic loader trampoline for the current state of thread.
std::vector< std::pair< ImageInfo, lldb::ModuleSP > > PreloadModulesFromImageInfos(const ImageInfo::collection &image_infos)
bool JSONImageInformationIntoImageInfo(lldb_private::StructuredData::ObjectSP image_details, ImageInfo::collection &image_infos)
bool UpdateImageLoadAddress(lldb_private::Module *module, ImageInfo &info)
std::optional< lldb_private::Address > GetStartAddress() override
Return the start address in the dynamic loader module.
void UpdateSpecialBinariesFromPreloadedModules(std::vector< std::pair< ImageInfo, lldb::ModuleSP > > &images)
void PrivateInitialize(lldb_private::Process *process)
lldb_private::Address GetPthreadSetSpecificAddress()
bool AddModulesUsingPreloadedModules(std::vector< std::pair< ImageInfo, lldb::ModuleSP > > &images)
void SetDYLDModule(lldb::ModuleSP &dyld_module_sp)
static bool UseDYLDSPI(lldb_private::Process *process)
lldb_private::Address m_pthread_getspecific_addr
bool UnloadModuleSections(lldb_private::Module *module, ImageInfo &info)
void UnloadImages(const std::vector< lldb::addr_t > &solib_addresses)
virtual bool DidSetNotificationBreakpoint()=0
Process * m_process
The process that this dynamic loader plug-in is tracking.
DynamicLoader(Process *process)
Construct with a process.
virtual bool GetSharedCacheInformation(lldb::addr_t &base_address, UUID &uuid, LazyBool &using_shared_cache, LazyBool &private_shared_cache, lldb_private::FileSpec &shared_cache_path, std::optional< uint64_t > &size)
Get information about the shared cache for a process, if possible.
virtual void UnloadSections(const lldb::ModuleSP module)
Removes the loaded sections from the target in module.
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
A file utility class.
Definition FileSpec.h:57
const ConstString & GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:250
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:374
ConstString GetPathAsConstString(bool denormalize=true) const
Get the full path as a ConstString.
Definition FileSpec.cpp:390
void SetFilename(ConstString filename)
Filename string set accessor.
Definition FileSpec.cpp:352
static FileSystem & Instance()
const Address & GetAddress() const
Return the address of the function (its entry point).
Definition Function.h:445
void PutCString(const char *cstr)
Definition Log.cpp:145
ConstString GetName(NamePreference preference=ePreferDemangled) const
Best name get accessor.
Definition Mangled.cpp:369
lldb::SymbolSharedCacheUse GetSharedCacheBinaryLoading() const
A collection class for Module objects.
Definition ModuleList.h:125
std::recursive_mutex & GetMutex() const
Definition ModuleList.h:252
lldb::ModuleSP FindFirstModule(const ModuleSpec &module_spec) const
Finds the first module whose file specification matches module_spec.
bool AppendIfNeeded(const lldb::ModuleSP &new_module, bool notify=true)
Append a module to the module list, if it is not already there.
void FindSymbolsWithNameAndType(ConstString name, lldb::SymbolType symbol_type, SymbolContextList &sc_list) const
static ModuleListProperties & GetGlobalModuleListProperties()
bool Remove(const lldb::ModuleSP &module_sp, bool notify=true)
Remove a module from the module list.
lldb::ModuleSP GetModuleAtIndex(size_t idx) const
Get the module shared pointer for the module at index idx.
void Append(const lldb::ModuleSP &module_sp, bool notify=true)
Append a module to the module list.
void FindSymbolsMatchingRegExAndType(const RegularExpression &regex, lldb::SymbolType symbol_type, SymbolContextList &sc_list) const
ModuleIterable Modules() const
Definition ModuleList.h:570
size_t GetSize() const
Gets the size of the module list.
void LogUUIDAndPaths(Log *log, const char *prefix_cstr)
void SetObjectSize(uint64_t object_size)
Definition ModuleSpec.h:119
ConstString & GetObjectName()
Definition ModuleSpec.h:107
FileSpec & GetFileSpec()
Definition ModuleSpec.h:57
ArchSpec & GetArchitecture()
Definition ModuleSpec.h:93
void SetObjectOffset(uint64_t object_offset)
Definition ModuleSpec.h:113
A class that describes an executable image and its associated object and symbol files.
Definition Module.h:90
virtual bool IsModuleObjCLibrary(const lldb::ModuleSP &module_sp)=0
static ObjCLanguageRuntime * Get(Process &process)
A plug-in interface definition class for object file parsers.
Definition ObjectFile.h:46
virtual lldb::addr_t GetFileOffset() const
Returns the offset into a file at which this object resides.
Definition ObjectFile.h:271
virtual FileSpec & GetFileSpec()
Get accessor to the object file specification.
Definition ObjectFile.h:280
virtual SectionList * GetSectionList(bool update_module_section_list=true)
Gets the section list for the currently selected architecture (and object for archives).
virtual lldb::addr_t GetByteSize() const
Definition ObjectFile.h:273
A plug-in interface definition class for debugging a process.
Definition Process.h:356
Range< lldb::addr_t, lldb::addr_t > LoadRange
Definition Process.h:388
virtual llvm::VersionTuple GetHostOSVersion()
Sometimes the connection to a process can detect the host OS version that the process is running on.
Definition Process.h:1244
virtual bool IsLiveDebugSession() const
Check if a process is a live debug session, or a corefile/post-mortem.
Definition Process.h:1534
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1254
bool Execute(llvm::StringRef string, llvm::SmallVectorImpl< llvm::StringRef > *matches=nullptr) const
Execute a regular expression match using the compiled regular expression that is already in this obje...
static lldb::TypeSystemClangSP GetForTarget(Target &target, std::optional< IsolatedASTKind > ast_kind=DefaultAST, bool create_on_demand=true)
Returns the scratch TypeSystemClang for the given target.
lldb::SectionSP FindSectionByName(ConstString section_dstr) const
Definition Section.cpp:556
lldb::offset_t GetFileOffset() const
Definition Section.h:181
This base class provides an interface to stack frames.
Definition StackFrame.h:44
virtual const SymbolContext & GetSymbolContext(lldb::SymbolContextItem resolve_scope)
Provide a SymbolContext for this StackFrame's current pc value.
An error handling class.
Definition Status.h:118
ObjectSP GetItemAtIndex(size_t idx) const
ObjectSP GetValueForKey(llvm::StringRef key) const
bool HasKey(llvm::StringRef key) const
std::shared_ptr< Object > ObjectSP
Defines a list of symbol context objects.
bool GetContextAtIndex(size_t idx, SymbolContext &sc) const
Get accessor for a symbol context at index idx.
Defines a symbol context baton that can be handed other debug core functions.
Function * function
The Function for a given query.
Symbol * symbol
The Symbol for a given query.
bool IsIndirect() const
Definition Symbol.cpp:223
Mangled & GetMangled()
Definition Symbol.h:147
bool IsTrampoline() const
Definition Symbol.cpp:221
Address & GetAddressRef()
Definition Symbol.h:73
ConstString GetName() const
Definition Symbol.cpp:511
lldb::SymbolType GetType() const
Definition Symbol.h:169
Address GetAddress() const
Definition Symbol.h:89
Symbol * ResolveReExportedSymbol(Target &target) const
Definition Symbol.cpp:483
Symbol * CalculateSymbolContextSymbol() override
Definition Symbol.cpp:414
Module * GetExecutableModulePointer()
Definition Target.cpp:1610
lldb::ModuleSP GetOrCreateModule(const ModuleSpec &module_spec, bool notify, Status *error_ptr=nullptr)
Find a binary on the system and return its Module, or return an existing Module that is already in th...
Definition Target.cpp:2410
bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr, uint32_t stop_id=SectionLoadHistory::eStopIDNow, bool allow_section_end=false)
Definition Target.cpp:3449
bool SetArchitecture(const ArchSpec &arch_spec, bool set_platform=false, bool merge=true)
Set the architecture for this target.
Definition Target.cpp:1756
lldb::ModuleSP GetExecutableModule()
Gets the module for the main executable.
Definition Target.cpp:1594
virtual size_t ReadMemory(const Address &addr, void *dst, size_t dst_len, Status &error, bool force_live_memory=false, lldb::addr_t *load_addr_ptr=nullptr, bool *did_read_live_memory=nullptr)
Definition Target.cpp:2062
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition Target.h:1240
const ArchSpec & GetArchitecture() const
Definition Target.h:1282
void SetExecutableModule(lldb::ModuleSP &module_sp, LoadDependentFiles load_dependent_files=eLoadDependentsDefault)
Set the main executable module.
Definition Target.cpp:1627
Represents UUID's of various sizes.
Definition UUID.h:27
bool IsValid() const
Definition UUID.h:69
#define LLDB_INVALID_ADDRESS
#define UINT32_MAX
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:327
const char * StateAsCString(lldb::StateType state)
Converts a StateType to a C string.
Definition State.cpp:14
std::shared_ptr< lldb_private::ThreadPlan > ThreadPlanSP
std::shared_ptr< lldb_private::Thread > ThreadSP
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
uint64_t offset_t
Definition lldb-types.h:85
StateType
Process and Thread States.
@ eStateUnloaded
Process is object is valid, but not currently loaded.
@ eStateConnected
Process is connected to remote debug services, but not launched or attached to anything yet.
@ eStateDetached
Process has been detached and can't be examined.
@ eStateStopped
Process or thread is stopped and can be examined.
@ eStateSuspended
Process or thread is in a suspended state as far as the debugger is concerned while other processes o...
@ eStateRunning
Process or thread is running and can't be examined.
@ eStateLaunching
Process is in the process of launching.
@ eStateAttaching
Process is currently trying to attach.
@ eStateExited
Process has exited and can't be examined.
@ eStateStepping
Process or thread is in the process of stepping and can not be examined.
@ eStateCrashed
Process or thread has crashed and can be examined.
ExpressionResults
The results of expression evaluation.
@ eExpressionCompleted
@ eSymbolTypeReExported
@ eSymbolTypeResolver
std::shared_ptr< lldb_private::TypeSystemClang > TypeSystemClangSP
std::shared_ptr< lldb_private::Section > SectionSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
uint64_t tid_t
Definition lldb-types.h:84
std::shared_ptr< lldb_private::Module > ModuleSP
lldb_private::UUID uuid
UUID for this dylib if it has one, else all zeros.
lldb::addr_t address
Address of mach header for this dylib.
std::string min_version_os_sdk
LC_VERSION_MIN_... SDK.
lldb::addr_t slide
The amount to slide all segments by if there is a global slide.
llvm::MachO::mach_header header
The mach header for this image.
llvm::Triple::OSType os_type
LC_VERSION_MIN_... load command os type.
std::vector< Segment > segments
All segment vmaddr and vmsize pairs for this executable (from memory of inferior).
const Segment * FindSegment(lldb_private::ConstString name) const
lldb_private::FileSpec file_spec
Resolved path for this dylib.
llvm::Triple::EnvironmentType os_env
LC_VERSION_MIN_... load command os environment.
uint32_t load_stop_id
The process stop ID that the sections for this image were loaded.
void PutToLog(lldb_private::Log *log) const
lldb::DataExtractorSP GetExtractor()
size_t vmsize
std::string name
uint64_t vmaddr