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;
147 if (GetSharedCacheInformation(sc_base_addr, sc_uuid, using_sc, private_sc,
148 sc_path) &&
149 sc_uuid) {
150 if (module_spec.GetUUID())
151 image_info = HostInfo::GetSharedCacheImageInfo(module_spec.GetUUID(),
152 sc_uuid, sc_mode);
153
154 else
155 image_info = HostInfo::GetSharedCacheImageInfo(
156 module_spec.GetFileSpec().GetPathAsConstString(), sc_uuid, sc_mode);
157 } else {
158 // Fall back to looking lldb's own shared cache by filename
159 image_info = HostInfo::GetSharedCacheImageInfo(
160 module_spec.GetFileSpec().GetPathAsConstString(), sc_mode);
161 }
162
163 // If we found it and it has the correct UUID, let's proceed with
164 // creating a module from the memory contents.
165 if (image_info.GetUUID() &&
166 (!module_spec.GetUUID() ||
167 module_spec.GetUUID() == image_info.GetUUID())) {
168 ModuleSpec shared_cache_spec(module_spec.GetFileSpec(),
169 image_info.GetUUID(),
170 image_info.GetExtractor());
171 module_sp =
172 target.GetOrCreateModule(shared_cache_spec, false /* notify */);
173 }
174 }
175 // We'll call Target::ModulesDidLoad after all the modules have been
176 // added to the target, don't let it be called for every one.
177 if (!module_sp || module_sp->GetObjectFile() == nullptr) {
178 llvm::Expected<ModuleSP> module_sp_or_err = m_process->ReadModuleFromMemory(
179 image_info.file_spec, image_info.address);
180 if (auto err = module_sp_or_err.takeError()) {
182 "Failed to load module from memory: {0}");
183 return {};
184 }
185 module_sp = *module_sp_or_err;
186 }
187
188 if (did_create_ptr)
189 *did_create_ptr = (bool)module_sp;
190
191 return module_sp;
192}
193
195 const std::vector<lldb::addr_t> &solib_addresses) {
196 std::lock_guard<std::recursive_mutex> guard(m_mutex);
197 if (m_process->GetStopID() == m_dyld_image_infos_stop_id)
198 return;
199
201 Target &target = m_process->GetTarget();
202 LLDB_LOGF(log, "Removing %" PRId64 " modules.",
203 (uint64_t)solib_addresses.size());
204
205 ModuleList unloaded_module_list;
206
207 for (addr_t solib_addr : solib_addresses) {
208 Address header;
209 if (header.SetLoadAddress(solib_addr, &target)) {
210 if (header.GetOffset() == 0) {
211 ModuleSP module_to_remove(header.GetModule());
212 if (module_to_remove.get()) {
213 LLDB_LOGF(log, "Removing module at address 0x%" PRIx64, solib_addr);
214 // remove the sections from the Target
215 UnloadSections(module_to_remove);
216 // add this to the list of modules to remove
217 unloaded_module_list.AppendIfNeeded(module_to_remove);
218 // remove the entry from the m_dyld_image_infos
219 ImageInfo::collection::iterator pos, end = m_dyld_image_infos.end();
220 for (pos = m_dyld_image_infos.begin(); pos != end; pos++) {
221 if (solib_addr == (*pos).address) {
222 m_dyld_image_infos.erase(pos);
223 break;
224 }
225 }
226 }
227 }
228 }
229 }
230
231 if (unloaded_module_list.GetSize() > 0) {
232 if (log) {
233 log->PutCString("Unloaded:");
234 unloaded_module_list.LogUUIDAndPaths(
235 log, "DynamicLoaderDarwin::UnloadModules");
236 }
237 m_process->GetTarget().GetImages().Remove(unloaded_module_list);
239 }
240}
241
244 ModuleList unloaded_modules_list;
245
246 Target &target = m_process->GetTarget();
247 const ModuleList &target_modules = target.GetImages();
248 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
249
250 ModuleSP dyld_sp(GetDYLDModule());
251 for (ModuleSP module_sp : target_modules.Modules()) {
252 // Don't remove dyld - else we'll lose our breakpoint notifying us about
253 // libraries being re-loaded...
254 if (module_sp && module_sp != dyld_sp) {
255 UnloadSections(module_sp);
256 unloaded_modules_list.Append(module_sp);
257 }
258 }
259
260 if (unloaded_modules_list.GetSize() != 0) {
261 if (log) {
262 log->PutCString("Unloaded:");
263 unloaded_modules_list.LogUUIDAndPaths(
264 log, "DynamicLoaderDarwin::UnloadAllImages");
265 }
266 target.GetImages().Remove(unloaded_modules_list);
267 m_dyld_image_infos.clear();
269 }
270}
271
272// Update the load addresses for all segments in MODULE using the updated INFO
273// that is passed in.
275 ImageInfo &info) {
276 bool changed = false;
277 if (module) {
278 ObjectFile *image_object_file = module->GetObjectFile();
279 if (image_object_file) {
280 SectionList *section_list = image_object_file->GetSectionList();
281 if (section_list) {
282 std::vector<uint32_t> inaccessible_segment_indexes;
283 // We now know the slide amount, so go through all sections and update
284 // the load addresses with the correct values.
285 const size_t num_segments = info.segments.size();
286 for (size_t i = 0; i < num_segments; ++i) {
287 // Only load a segment if it has protections. Things like __PAGEZERO
288 // don't have any protections, and they shouldn't be slid
289 SectionSP section_sp(
290 section_list->FindSectionByName(info.segments[i].name));
291
292 if (info.segments[i].maxprot == 0) {
293 inaccessible_segment_indexes.push_back(i);
294 } else {
295 const addr_t new_section_load_addr =
296 info.segments[i].vmaddr + info.slide;
297 static ConstString g_section_name_LINKEDIT("__LINKEDIT");
298
299 if (section_sp) {
300 // __LINKEDIT sections from files in the shared cache can overlap
301 // so check to see what the segment name is and pass "false" so
302 // we don't warn of overlapping "Section" objects, and "true" for
303 // all other sections.
304 const bool warn_multiple =
305 section_sp->GetName() != g_section_name_LINKEDIT;
306
307 changed = m_process->GetTarget().SetSectionLoadAddress(
308 section_sp, new_section_load_addr, warn_multiple);
309 }
310 }
311 }
312
313 // If the loaded the file (it changed) and we have segments that are
314 // not readable or writeable, add them to the invalid memory region
315 // cache for the process. This will typically only be the __PAGEZERO
316 // segment in the main executable. We might be able to apply this more
317 // generally to more sections that have no protections in the future,
318 // but for now we are going to just do __PAGEZERO.
319 if (changed && !inaccessible_segment_indexes.empty()) {
320 for (uint32_t i = 0; i < inaccessible_segment_indexes.size(); ++i) {
321 const uint32_t seg_idx = inaccessible_segment_indexes[i];
322 SectionSP section_sp(
323 section_list->FindSectionByName(info.segments[seg_idx].name));
324
325 if (section_sp) {
326 static ConstString g_pagezero_section_name("__PAGEZERO");
327 if (g_pagezero_section_name == section_sp->GetName()) {
328 // __PAGEZERO never slides...
329 const lldb::addr_t vmaddr = info.segments[seg_idx].vmaddr;
330 const lldb::addr_t vmsize = info.segments[seg_idx].vmsize;
331 Process::LoadRange pagezero_range(vmaddr, vmsize);
332 m_process->AddInvalidMemoryRegion(pagezero_range);
333 }
334 }
335 }
336 }
337 }
338 }
339 }
340 // We might have an in memory image that was loaded as soon as it was created
341 if (info.load_stop_id == m_process->GetStopID())
342 changed = true;
343 else if (changed) {
344 // Update the stop ID when this library was updated
345 info.load_stop_id = m_process->GetStopID();
346 }
347 return changed;
348}
349
350// Unload the segments in MODULE using the INFO that is passed in.
352 ImageInfo &info) {
353 bool changed = false;
354 if (module) {
355 ObjectFile *image_object_file = module->GetObjectFile();
356 if (image_object_file) {
357 SectionList *section_list = image_object_file->GetSectionList();
358 if (section_list) {
359 const size_t num_segments = info.segments.size();
360 for (size_t i = 0; i < num_segments; ++i) {
361 SectionSP section_sp(
362 section_list->FindSectionByName(info.segments[i].name));
363 if (section_sp) {
364 const addr_t old_section_load_addr =
365 info.segments[i].vmaddr + info.slide;
366 if (m_process->GetTarget().SetSectionUnloaded(
367 section_sp, old_section_load_addr))
368 changed = true;
369 } else {
371 llvm::formatv("unable to find and unload segment named "
372 "'{0}' in '{1}' in macosx dynamic loader plug-in",
373 info.segments[i].name.AsCString("<invalid>"),
374 image_object_file->GetFileSpec().GetPath()));
375 }
376 }
377 }
378 }
379 }
380 return changed;
381}
382
383// Given a JSON dictionary (from debugserver, most likely) of binary images
384// loaded in the inferior process, add the images to the ImageInfo collection.
385
387 StructuredData::ObjectSP image_details,
388 ImageInfo::collection &image_infos) {
389 StructuredData::ObjectSP images_sp =
390 image_details->GetAsDictionary()->GetValueForKey("images");
391 if (images_sp.get() == nullptr)
392 return false;
393
394 image_infos.resize(images_sp->GetAsArray()->GetSize());
395
396 for (size_t i = 0; i < image_infos.size(); i++) {
397 StructuredData::ObjectSP image_sp =
398 images_sp->GetAsArray()->GetItemAtIndex(i);
399 if (image_sp.get() == nullptr || image_sp->GetAsDictionary() == nullptr)
400 return false;
401 StructuredData::Dictionary *image = image_sp->GetAsDictionary();
402 // clang-format off
403 if (!image->HasKey("load_address") ||
404 !image->HasKey("pathname") ||
405 !image->HasKey("mach_header") ||
406 image->GetValueForKey("mach_header")->GetAsDictionary() == nullptr ||
407 !image->HasKey("segments") ||
408 image->GetValueForKey("segments")->GetAsArray() == nullptr ||
409 !image->HasKey("uuid")) {
410 return false;
411 }
412 // clang-format on
413 image_infos[i].address =
414 image->GetValueForKey("load_address")->GetUnsignedIntegerValue();
415 image_infos[i].file_spec.SetFile(
416 image->GetValueForKey("pathname")->GetAsString()->GetValue(),
417 FileSpec::Style::native);
418
420 image->GetValueForKey("mach_header")->GetAsDictionary();
421 image_infos[i].header.magic =
422 mh->GetValueForKey("magic")->GetUnsignedIntegerValue();
423 image_infos[i].header.cputype =
424 mh->GetValueForKey("cputype")->GetUnsignedIntegerValue();
425 image_infos[i].header.cpusubtype =
426 mh->GetValueForKey("cpusubtype")->GetUnsignedIntegerValue();
427 image_infos[i].header.filetype =
428 mh->GetValueForKey("filetype")->GetUnsignedIntegerValue();
429
430 if (image->HasKey("min_version_os_name")) {
431 std::string os_name =
432 std::string(image->GetValueForKey("min_version_os_name")
433 ->GetAsString()
434 ->GetValue());
435 if (os_name == "macosx")
436 image_infos[i].os_type = llvm::Triple::MacOSX;
437 else if (os_name == "ios" || os_name == "iphoneos")
438 image_infos[i].os_type = llvm::Triple::IOS;
439 else if (os_name == "tvos")
440 image_infos[i].os_type = llvm::Triple::TvOS;
441 else if (os_name == "watchos")
442 image_infos[i].os_type = llvm::Triple::WatchOS;
443 else if (os_name == "bridgeos")
444 image_infos[i].os_type = llvm::Triple::BridgeOS;
445 else if (os_name == "driverkit")
446 image_infos[i].os_type = llvm::Triple::DriverKit;
447 else if (os_name == "xros")
448 image_infos[i].os_type = llvm::Triple::XROS;
449 else if (os_name == "maccatalyst") {
450 image_infos[i].os_type = llvm::Triple::IOS;
451 image_infos[i].os_env = llvm::Triple::MacABI;
452 } else if (os_name == "iossimulator") {
453 image_infos[i].os_type = llvm::Triple::IOS;
454 image_infos[i].os_env = llvm::Triple::Simulator;
455 } else if (os_name == "tvossimulator") {
456 image_infos[i].os_type = llvm::Triple::TvOS;
457 image_infos[i].os_env = llvm::Triple::Simulator;
458 } else if (os_name == "watchossimulator") {
459 image_infos[i].os_type = llvm::Triple::WatchOS;
460 image_infos[i].os_env = llvm::Triple::Simulator;
461 } else if (os_name == "xrsimulator") {
462 image_infos[i].os_type = llvm::Triple::XROS;
463 image_infos[i].os_env = llvm::Triple::Simulator;
464 }
465 }
466 if (image->HasKey("min_version_os_sdk")) {
467 image_infos[i].min_version_os_sdk =
468 std::string(image->GetValueForKey("min_version_os_sdk")
469 ->GetAsString()
470 ->GetValue());
471 }
472
473 // Fields that aren't used by DynamicLoaderDarwin so debugserver doesn't
474 // currently send them in the reply.
475
476 if (mh->HasKey("flags"))
477 image_infos[i].header.flags =
478 mh->GetValueForKey("flags")->GetUnsignedIntegerValue();
479 else
480 image_infos[i].header.flags = 0;
481
482 if (mh->HasKey("ncmds"))
483 image_infos[i].header.ncmds =
484 mh->GetValueForKey("ncmds")->GetUnsignedIntegerValue();
485 else
486 image_infos[i].header.ncmds = 0;
487
488 if (mh->HasKey("sizeofcmds"))
489 image_infos[i].header.sizeofcmds =
490 mh->GetValueForKey("sizeofcmds")->GetUnsignedIntegerValue();
491 else
492 image_infos[i].header.sizeofcmds = 0;
493
494 StructuredData::Array *segments =
495 image->GetValueForKey("segments")->GetAsArray();
496 uint32_t segcount = segments->GetSize();
497 for (size_t j = 0; j < segcount; j++) {
500 segments->GetItemAtIndex(j)->GetAsDictionary();
501 segment.name =
502 ConstString(seg->GetValueForKey("name")->GetAsString()->GetValue());
503 segment.vmaddr = seg->GetValueForKey("vmaddr")->GetUnsignedIntegerValue();
504 segment.vmsize = seg->GetValueForKey("vmsize")->GetUnsignedIntegerValue();
505 segment.fileoff =
506 seg->GetValueForKey("fileoff")->GetUnsignedIntegerValue();
507 segment.filesize =
508 seg->GetValueForKey("filesize")->GetUnsignedIntegerValue();
509 segment.maxprot =
510 seg->GetValueForKey("maxprot")->GetUnsignedIntegerValue();
511
512 // Fields that aren't used by DynamicLoaderDarwin so debugserver doesn't
513 // currently send them in the reply.
514
515 if (seg->HasKey("initprot"))
516 segment.initprot =
517 seg->GetValueForKey("initprot")->GetUnsignedIntegerValue();
518 else
519 segment.initprot = 0;
520
521 if (seg->HasKey("flags"))
522 segment.flags = seg->GetValueForKey("flags")->GetUnsignedIntegerValue();
523 else
524 segment.flags = 0;
525
526 if (seg->HasKey("nsects"))
527 segment.nsects =
528 seg->GetValueForKey("nsects")->GetUnsignedIntegerValue();
529 else
530 segment.nsects = 0;
531
532 image_infos[i].segments.push_back(segment);
533 }
534
535 image_infos[i].uuid.SetFromStringRef(
536 image->GetValueForKey("uuid")->GetAsString()->GetValue());
537
538 // All sections listed in the dyld image info structure will all either be
539 // fixed up already, or they will all be off by a single slide amount that
540 // is determined by finding the first segment that is at file offset zero
541 // which also has bytes (a file size that is greater than zero) in the
542 // object file.
543
544 // Determine the slide amount (if any)
545 const size_t num_sections = image_infos[i].segments.size();
546 for (size_t k = 0; k < num_sections; ++k) {
547 // Iterate through the object file sections to find the first section
548 // that starts of file offset zero and that has bytes in the file...
549 if ((image_infos[i].segments[k].fileoff == 0 &&
550 image_infos[i].segments[k].filesize > 0) ||
551 (image_infos[i].segments[k].name == "__TEXT")) {
552 image_infos[i].slide =
553 image_infos[i].address - image_infos[i].segments[k].vmaddr;
554 // We have found the slide amount, so we can exit this for loop.
555 break;
556 }
557 }
558 }
559
560 return true;
561}
562
564 std::vector<std::pair<ImageInfo, ModuleSP>> &images) {
565 uint32_t exe_idx = UINT32_MAX;
566 uint32_t dyld_idx = UINT32_MAX;
567 Target &target = m_process->GetTarget();
569 ConstString g_dyld_sim_filename("dyld_sim");
570
571 ArchSpec target_arch = target.GetArchitecture();
572 const size_t images_size = images.size();
573 for (size_t i = 0; i < images_size; i++) {
574 const auto &image_info = images[i].first;
575 if (image_info.header.filetype == llvm::MachO::MH_DYLINKER) {
576 // In a "simulator" process we will have two dyld modules --
577 // a "dyld" that we want to keep track of, and a "dyld_sim" which
578 // we don't need to keep track of here. dyld_sim will have a non-macosx
579 // OS.
580 if (target_arch.GetTriple().getEnvironment() == llvm::Triple::Simulator &&
581 image_info.os_type != llvm::Triple::OSType::MacOSX) {
582 continue;
583 }
584
585 dyld_idx = i;
586 }
587 if (image_info.header.filetype == llvm::MachO::MH_EXECUTE) {
588 exe_idx = i;
589 }
590 }
591
592 // Set the target executable if we haven't found one so far.
593 if (exe_idx != UINT32_MAX && !target.GetExecutableModule()) {
594 ModuleSP exe_module_sp = images[exe_idx].second;
595 if (exe_module_sp) {
596 LLDB_LOGF(log, "Found executable module: %s",
597 exe_module_sp->GetFileSpec().GetPath().c_str());
598 target.GetImages().AppendIfNeeded(exe_module_sp);
599 UpdateImageLoadAddress(exe_module_sp.get(), images[exe_idx].first);
600 if (exe_module_sp.get() != target.GetExecutableModulePointer())
601 target.SetExecutableModule(exe_module_sp, eLoadDependentsNo);
602
603 // Update the target executable's arch if necessary.
604 auto exe_triple = exe_module_sp->GetArchitecture().GetTriple();
605 if (target_arch.GetTriple().isArm64e() &&
606 exe_triple.getArch() == llvm::Triple::aarch64 &&
607 !exe_triple.isArm64e()) {
608 // On arm64e-capable Apple platforms, the system libraries are
609 // always arm64e, but applications often are arm64. When a
610 // target is created from a file, LLDB recognizes it as an
611 // arm64 target, but debugserver will still (technically
612 // correct) report the process as being arm64e. For
613 // consistency, set the target to arm64 here, so attaching to
614 // a live process behaves the same as creating a process from
615 // file.
616 auto triple = target_arch.GetTriple();
617 triple.setArchName(exe_triple.getArchName());
618 target_arch.SetTriple(triple);
619 target.SetArchitecture(target_arch, /*set_platform=*/false,
620 /*merge=*/false);
621 }
622 }
623 }
624
625 if (dyld_idx != UINT32_MAX) {
626 ModuleSP dyld_sp = images[dyld_idx].second;
627 if (dyld_sp.get()) {
628 LLDB_LOGF(log, "Found dyld module: %s",
629 dyld_sp->GetFileSpec().GetPath().c_str());
630 target.GetImages().AppendIfNeeded(dyld_sp);
631 UpdateImageLoadAddress(dyld_sp.get(), images[dyld_idx].first);
632 SetDYLDModule(dyld_sp);
633 }
634 }
635}
636
638 ImageInfo &image_info) {
639 if (image_info.header.filetype == llvm::MachO::MH_DYLINKER) {
640 const bool can_create = true;
641 ModuleSP dyld_sp =
642 FindTargetModuleForImageInfo(image_info, can_create, nullptr);
643 if (dyld_sp.get()) {
644 Target &target = m_process->GetTarget();
645 target.GetImages().AppendIfNeeded(dyld_sp);
646 UpdateImageLoadAddress(dyld_sp.get(), image_info);
647 SetDYLDModule(dyld_sp);
648 return true;
649 }
650 }
651 return false;
652}
653
654std::optional<lldb_private::Address> DynamicLoaderDarwin::GetStartAddress() {
656
657 auto log_err = [log](llvm::StringLiteral err_msg) -> std::nullopt_t {
658 LLDB_LOGV(log, "{}", err_msg);
659 return std::nullopt;
660 };
661
662 ModuleSP dyld_sp = GetDYLDModule();
663 if (!dyld_sp)
664 return log_err("Couldn't retrieve DYLD module. Cannot get `start` symbol.");
665
666 const Symbol *symbol =
667 dyld_sp->FindFirstSymbolWithNameAndType(ConstString("_dyld_start"));
668 if (!symbol)
669 return log_err("Cannot find `start` symbol in DYLD module.");
670
671 return symbol->GetAddress();
672}
673
675 m_dyld_module_wp = dyld_module_sp;
676}
677
679 ModuleSP dyld_sp(m_dyld_module_wp.lock());
680 return dyld_sp;
681}
682
684
685std::vector<std::pair<DynamicLoaderDarwin::ImageInfo, ModuleSP>>
687 const ImageInfo::collection &image_infos) {
688 const auto size = image_infos.size();
689 std::vector<std::pair<DynamicLoaderDarwin::ImageInfo, ModuleSP>> images(size);
690 auto LoadImage = [&](size_t i, ImageInfo::collection::const_iterator it) {
691 const auto &image_info = *it;
692 images[i] = std::make_pair(
693 image_info, FindTargetModuleForImageInfo(image_info, true, nullptr));
694 };
695 auto it = image_infos.begin();
696 bool is_parallel_load = m_process->GetTarget().GetParallelModuleLoad();
697 if (is_parallel_load) {
698 llvm::ThreadPoolTaskGroup taskGroup(Debugger::GetThreadPool());
699 for (size_t i = 0; i < size; ++i, ++it) {
700 taskGroup.async(LoadImage, i, it);
701 }
702 taskGroup.wait();
703 } else {
704 for (size_t i = 0; i < size; ++i, ++it) {
705 LoadImage(i, it);
706 }
707 }
708 return images;
709}
710
712 ImageInfo::collection &image_infos) {
713 std::lock_guard<std::recursive_mutex> guard(m_mutex);
714 auto images = PreloadModulesFromImageInfos(image_infos);
715 return AddModulesUsingPreloadedModules(images);
716}
717
719 std::vector<std::pair<ImageInfo, ModuleSP>> &images) {
720 std::lock_guard<std::recursive_mutex> guard(m_mutex);
721 // Now add these images to the main list.
722 ModuleList loaded_module_list;
724 Target &target = m_process->GetTarget();
725 ModuleList &target_images = target.GetImages();
726
727 for (uint32_t idx = 0; idx < images.size(); ++idx) {
728 auto &image_info = images[idx].first;
729 const auto &image_module_sp = images[idx].second;
730 if (log) {
731 LLDB_LOGF(log, "Adding new image at address=0x%16.16" PRIx64 ".",
732 image_info.address);
733 image_info.PutToLog(log);
734 }
735 m_dyld_image_infos.push_back(image_info);
736
737 if (image_module_sp) {
738 ObjectFile *objfile = image_module_sp->GetObjectFile();
739 if (objfile) {
740 SectionList *sections = objfile->GetSectionList();
741 if (sections) {
742 ConstString commpage_dbstr("__commpage");
743 Section *commpage_section =
744 sections->FindSectionByName(commpage_dbstr).get();
745 if (commpage_section) {
746 ModuleSpec module_spec(objfile->GetFileSpec(),
747 image_info.GetArchitecture());
748 module_spec.GetObjectName() = commpage_dbstr;
749 ModuleSP commpage_image_module_sp(
750 target_images.FindFirstModule(module_spec));
751 if (!commpage_image_module_sp) {
752 module_spec.SetObjectOffset(objfile->GetFileOffset() +
753 commpage_section->GetFileOffset());
754 module_spec.SetObjectSize(objfile->GetByteSize());
755 commpage_image_module_sp = target.GetOrCreateModule(module_spec,
756 true /* notify */);
757 if (!commpage_image_module_sp ||
758 commpage_image_module_sp->GetObjectFile() == nullptr) {
759 llvm::Expected<ModuleSP> module_sp_or_err =
760 m_process->ReadModuleFromMemory(image_info.file_spec,
761 image_info.address);
762 if (auto err = module_sp_or_err.takeError()) {
763 LLDB_LOG_ERROR(log, std::move(err),
764 "Failed to read module from memory: {0}");
765 } else {
766 // Always load a memory image right away in the target in case
767 // we end up trying to read the symbol table from memory...
768 // The __LINKEDIT will need to be mapped so we can figure out
769 // where the symbol table bits are...
770 commpage_image_module_sp = *module_sp_or_err;
771 bool changed = false;
772 UpdateImageLoadAddress(commpage_image_module_sp.get(),
773 image_info);
774 target.GetImages().Append(commpage_image_module_sp);
775 if (changed) {
776 image_info.load_stop_id = m_process->GetStopID();
777 loaded_module_list.AppendIfNeeded(commpage_image_module_sp);
778 }
779 }
780 }
781 }
782 }
783 }
784 }
785
786 // UpdateImageLoadAddress will return true if any segments change load
787 // address. We need to check this so we don't mention that all loaded
788 // shared libraries are newly loaded each time we hit out dyld breakpoint
789 // since dyld will list all shared libraries each time.
790 if (UpdateImageLoadAddress(image_module_sp.get(), image_info)) {
791 target_images.AppendIfNeeded(image_module_sp);
792 loaded_module_list.AppendIfNeeded(image_module_sp);
793 }
794
795 // To support macCatalyst and legacy iOS simulator,
796 // update the module's platform with the DYLD info.
797 ArchSpec dyld_spec = image_info.GetArchitecture();
798 auto &dyld_triple = dyld_spec.GetTriple();
799 if ((dyld_triple.getEnvironment() == llvm::Triple::MacABI &&
800 dyld_triple.getOS() == llvm::Triple::IOS) ||
801 (dyld_triple.getEnvironment() == llvm::Triple::Simulator &&
802 (dyld_triple.getOS() == llvm::Triple::IOS ||
803 dyld_triple.getOS() == llvm::Triple::TvOS ||
804 dyld_triple.getOS() == llvm::Triple::WatchOS ||
805 dyld_triple.getOS() == llvm::Triple::XROS)))
806 image_module_sp->MergeArchitecture(dyld_spec);
807 }
808 }
809
810 if (loaded_module_list.GetSize() > 0) {
811 if (log)
812 loaded_module_list.LogUUIDAndPaths(log,
813 "DynamicLoaderDarwin::ModulesDidLoad");
814 m_process->GetTarget().ModulesDidLoad(loaded_module_list);
815 }
816 return true;
817}
818
819// On Mac OS X libobjc (the Objective-C runtime) has several critical dispatch
820// functions written in hand-written assembly, and also have hand-written
821// unwind information in the eh_frame section. Normally we prefer analyzing
822// the assembly instructions of a currently executing frame to unwind from that
823// frame -- but on hand-written functions this profiling can fail. We should
824// use the eh_frame instructions for these functions all the time.
825//
826// As an aside, it would be better if the eh_frame entries had a flag (or were
827// extensible so they could have an Apple-specific flag) which indicates that
828// the instructions are asynchronous -- accurate at every instruction, instead
829// of our normal default assumption that they are not.
830
832 ModuleSP module_sp;
833 if (sym_ctx.symbol) {
834 module_sp = sym_ctx.symbol->GetAddressRef().GetModule();
835 }
836 if (module_sp.get() == nullptr && sym_ctx.function)
837 module_sp = sym_ctx.function->GetAddress().GetModule();
838 if (module_sp.get() == nullptr)
839 return false;
840
842 return objc_runtime != nullptr &&
843 objc_runtime->IsModuleObjCLibrary(module_sp);
844}
845
846// Dump a Segment to the file handle provided.
848 lldb::addr_t slide) const {
849 if (log) {
850 if (slide == 0)
851 LLDB_LOGF(log, "\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ")",
852 name.AsCString(""), vmaddr + slide, vmaddr + slide + vmsize);
853 else
854 LLDB_LOGF(log,
855 "\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64
856 ") slide = 0x%" PRIx64,
857 name.AsCString(""), vmaddr + slide, vmaddr + slide + vmsize,
858 slide);
859 }
860}
861
863 // Update the module's platform with the DYLD info.
865 header.cpusubtype);
866 if (os_env == llvm::Triple::MacABI && os_type == llvm::Triple::IOS) {
867 llvm::Triple triple(llvm::Twine(arch_spec.GetArchitectureName()) +
868 "-apple-ios" + min_version_os_sdk + "-macabi");
869 ArchSpec maccatalyst_spec(triple);
870 if (arch_spec.IsCompatibleMatch(maccatalyst_spec))
871 arch_spec.MergeFrom(maccatalyst_spec);
872 }
873 if (os_env == llvm::Triple::Simulator &&
874 (os_type == llvm::Triple::IOS || os_type == llvm::Triple::TvOS ||
875 os_type == llvm::Triple::WatchOS || os_type == llvm::Triple::XROS)) {
876 llvm::Triple triple(llvm::Twine(arch_spec.GetArchitectureName()) +
877 "-apple-" + llvm::Triple::getOSTypeName(os_type) +
878 min_version_os_sdk + "-simulator");
879 ArchSpec sim_spec(triple);
880 if (arch_spec.IsCompatibleMatch(sim_spec))
881 arch_spec.MergeFrom(sim_spec);
882 }
883 return arch_spec;
884}
885
888 const size_t num_segments = segments.size();
889 for (size_t i = 0; i < num_segments; ++i) {
890 if (segments[i].name == name)
891 return &segments[i];
892 }
893 return nullptr;
894}
895
896// Dump an image info structure to the file handle provided.
898 if (!log)
899 return;
901 LLDB_LOG(log, "uuid={1} path='{2}' (UNLOADED)", uuid.GetAsString(),
902 file_spec.GetPath());
903 } else {
904 LLDB_LOG(log, "address={0:x+16} uuid={1} path='{2}'", address,
905 uuid.GetAsString(), file_spec.GetPath());
906 for (uint32_t i = 0; i < segments.size(); ++i)
907 segments[i].PutToLog(log, slide);
908 }
909}
910
912 DEBUG_PRINTF("DynamicLoaderDarwin::%s() process state = %s\n", __FUNCTION__,
913 StateAsCString(m_process->GetState()));
914 Clear(true);
915 m_process = process;
916}
917
918// Member function that gets called when the process state changes.
920 StateType state) {
921 DEBUG_PRINTF("DynamicLoaderDarwin::%s(%s)\n", __FUNCTION__,
922 StateAsCString(state));
923 switch (state) {
924 case eStateConnected:
925 case eStateAttaching:
926 case eStateLaunching:
927 case eStateInvalid:
928 case eStateUnloaded:
929 case eStateExited:
930 case eStateDetached:
931 Clear(false);
932 break;
933
934 case eStateStopped:
935 // Keep trying find dyld and set our notification breakpoint each time we
936 // stop until we succeed
937 if (!DidSetNotificationBreakpoint() && m_process->IsAlive()) {
940
942 }
943 break;
944
945 case eStateRunning:
946 case eStateStepping:
947 case eStateCrashed:
948 case eStateSuspended:
949 break;
950 }
951}
952
955 bool stop_others) {
956 ThreadPlanSP thread_plan_sp;
957 StackFrame *current_frame = thread.GetStackFrameAtIndex(0).get();
958 const SymbolContext &current_context =
959 current_frame->GetSymbolContext(eSymbolContextSymbol);
960 const Symbol *current_symbol = current_context.symbol;
961 Log *log = GetLog(LLDBLog::Step);
962 TargetSP target_sp(thread.CalculateTarget());
963
964 if (current_symbol != nullptr) {
965 std::vector<Address> addresses;
966
967 ConstString current_name =
968 current_symbol->GetMangled().GetName(Mangled::ePreferMangled);
969 if (current_symbol->IsTrampoline()) {
970
971 if (current_name) {
972 const ModuleList &images = target_sp->GetImages();
973
974 SymbolContextList code_symbols;
975 images.FindSymbolsWithNameAndType(current_name, eSymbolTypeCode,
976 code_symbols);
977 for (const SymbolContext &context : code_symbols) {
978 Address addr = context.GetFunctionOrSymbolAddress();
979 addresses.push_back(addr);
980 if (log) {
981 addr_t load_addr = addr.GetLoadAddress(target_sp.get());
982
983 LLDB_LOGF(log, "Found a trampoline target symbol at 0x%" PRIx64 ".",
984 load_addr);
985 }
986 }
987
988 SymbolContextList reexported_symbols;
990 reexported_symbols);
991 for (const SymbolContext &context : reexported_symbols) {
992 if (context.symbol) {
993 const Symbol *actual_symbol =
994 context.symbol->ResolveReExportedSymbol(*target_sp.get());
995 if (actual_symbol) {
996 const Address actual_symbol_addr = actual_symbol->GetAddress();
997 if (actual_symbol_addr.IsValid()) {
998 addresses.push_back(actual_symbol_addr);
999 if (log) {
1000 lldb::addr_t load_addr =
1001 actual_symbol_addr.GetLoadAddress(target_sp.get());
1002 LLDB_LOGF(log,
1003 "Found a re-exported symbol: %s at 0x%" PRIx64 ".",
1004 actual_symbol->GetName().GetCString(), load_addr);
1005 }
1006 }
1007 }
1008 }
1009 }
1010
1011 SymbolContextList indirect_symbols;
1013 indirect_symbols);
1014
1015 for (const SymbolContext &context : indirect_symbols) {
1016 Address addr = context.GetFunctionOrSymbolAddress();
1017 addresses.push_back(addr);
1018 if (log) {
1019 addr_t load_addr = addr.GetLoadAddress(target_sp.get());
1020
1021 LLDB_LOGF(log, "Found an indirect target symbol at 0x%" PRIx64 ".",
1022 load_addr);
1023 }
1024 }
1025 }
1026 } else if (current_symbol->GetType() == eSymbolTypeReExported) {
1027 // I am not sure we could ever end up stopped AT a re-exported symbol.
1028 // But just in case:
1029
1030 const Symbol *actual_symbol =
1031 current_symbol->ResolveReExportedSymbol(*(target_sp.get()));
1032 if (actual_symbol) {
1033 Address target_addr(actual_symbol->GetAddress());
1034 if (target_addr.IsValid()) {
1035 LLDB_LOGF(
1036 log,
1037 "Found a re-exported symbol: %s pointing to: %s at 0x%" PRIx64
1038 ".",
1039 current_symbol->GetName().GetCString(),
1040 actual_symbol->GetName().GetCString(),
1041 target_addr.GetLoadAddress(target_sp.get()));
1042 addresses.push_back(target_addr.GetLoadAddress(target_sp.get()));
1043 }
1044 }
1045 }
1046
1047 if (addresses.size() > 0) {
1048 // First check whether any of the addresses point to Indirect symbols,
1049 // and if they do, resolve them:
1050 std::vector<lldb::addr_t> load_addrs;
1051 for (Address address : addresses) {
1052 const Symbol *symbol = address.CalculateSymbolContextSymbol();
1053 if (symbol && symbol->IsIndirect()) {
1054 Status error;
1055 Address symbol_address = symbol->GetAddress();
1056 addr_t resolved_addr = thread.GetProcess()->ResolveIndirectFunction(
1057 &symbol_address, error);
1058 if (error.Success()) {
1059 load_addrs.push_back(resolved_addr);
1060 LLDB_LOGF(log,
1061 "ResolveIndirectFunction found resolved target for "
1062 "%s at 0x%" PRIx64 ".",
1063 symbol->GetName().GetCString(), resolved_addr);
1064 }
1065 } else {
1066 load_addrs.push_back(address.GetLoadAddress(target_sp.get()));
1067 }
1068 }
1069 thread_plan_sp = std::make_shared<ThreadPlanRunToAddress>(
1070 thread, load_addrs, stop_others);
1071 }
1072 // One more case we have to consider is "branch islands". These are regular
1073 // TEXT symbols but their names end in .island plus maybe a .digit suffix.
1074 // They are to allow arm64 code to branch further than the size of the
1075 // address slot allows. We just need to single-instruction step in that
1076 // case.
1077 static const char *g_branch_island_pattern = "\\.island\\.?[0-9]*$";
1078 static RegularExpression g_branch_island_regex(g_branch_island_pattern);
1079
1080 bool is_branch_island = g_branch_island_regex.Execute(current_name);
1081 if (!thread_plan_sp && is_branch_island) {
1082 thread_plan_sp = std::make_shared<ThreadPlanStepInstruction>(
1083 thread,
1084 /* step_over= */ false, /* stop_others */ false, eVoteNoOpinion,
1086 LLDB_LOG(log, "Stepping one instruction over branch island: '{0}'.",
1087 current_name);
1088 }
1089 } else {
1090 LLDB_LOGF(log, "Could not find symbol for step through.");
1091 }
1092
1093 return thread_plan_sp;
1094}
1095
1097 const lldb_private::Symbol *original_symbol,
1099 lldb_private::SymbolContextList &equivalent_symbols) {
1100 ConstString trampoline_name =
1101 original_symbol->GetMangled().GetName(Mangled::ePreferMangled);
1102 if (!trampoline_name)
1103 return;
1104
1105 static const char *resolver_name_regex = "(_gc|_non_gc|\\$[A-Za-z0-9\\$]+)$";
1106 std::string equivalent_regex_buf("^");
1107 equivalent_regex_buf.append(trampoline_name.GetCString());
1108 equivalent_regex_buf.append(resolver_name_regex);
1109
1110 RegularExpression equivalent_name_regex(equivalent_regex_buf);
1111 images.FindSymbolsMatchingRegExAndType(equivalent_name_regex, eSymbolTypeCode,
1112 equivalent_symbols);
1113}
1114
1116 ModuleSP module_sp = m_libpthread_module_wp.lock();
1117 if (!module_sp) {
1118 SymbolContextList sc_list;
1119 ModuleSpec module_spec;
1120 module_spec.GetFileSpec().SetFilename("libsystem_pthread.dylib");
1121 ModuleList module_list;
1122 m_process->GetTarget().GetImages().FindModules(module_spec, module_list);
1123 if (!module_list.IsEmpty()) {
1124 if (module_list.GetSize() == 1) {
1125 module_sp = module_list.GetModuleAtIndex(0);
1126 if (module_sp)
1127 m_libpthread_module_wp = module_sp;
1128 }
1129 }
1130 }
1131 return module_sp;
1132}
1133
1135 if (!m_pthread_getspecific_addr.IsValid()) {
1136 ModuleSP module_sp = GetPThreadLibraryModule();
1137 if (module_sp) {
1139 module_sp->FindSymbolsWithNameAndType(ConstString("pthread_getspecific"),
1140 eSymbolTypeCode, sc_list);
1141 SymbolContext sc;
1142 if (sc_list.GetContextAtIndex(0, sc)) {
1143 if (sc.symbol)
1145 }
1146 }
1147 }
1149}
1150
1153 const lldb::ThreadSP thread_sp,
1154 lldb::addr_t tls_file_addr) {
1155 if (!thread_sp || !module_sp)
1156 return LLDB_INVALID_ADDRESS;
1157
1158 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1159
1160 lldb_private::Address tls_addr;
1161 if (!module_sp->ResolveFileAddress(tls_file_addr, tls_addr))
1162 return LLDB_INVALID_ADDRESS;
1163
1164 Target &target = m_process->GetTarget();
1165 TypeSystemClangSP scratch_ts_sp =
1167 if (!scratch_ts_sp)
1168 return LLDB_INVALID_ADDRESS;
1169
1170 CompilerType clang_void_ptr_type =
1171 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
1172
1173 auto evaluate_tls_address = [this, &thread_sp, &clang_void_ptr_type](
1174 Address func_ptr,
1175 llvm::ArrayRef<addr_t> args) -> addr_t {
1177
1178 lldb::ThreadPlanSP thread_plan_sp(new ThreadPlanCallFunction(
1179 *thread_sp, func_ptr, clang_void_ptr_type, args, options));
1180
1181 DiagnosticManager execution_errors;
1182 ExecutionContext exe_ctx(thread_sp);
1183 lldb::ExpressionResults results = m_process->RunThreadPlan(
1184 exe_ctx, thread_plan_sp, options, execution_errors);
1185
1186 if (results == lldb::eExpressionCompleted) {
1187 if (lldb::ValueObjectSP result_valobj_sp =
1188 thread_plan_sp->GetReturnValueObject()) {
1189 return result_valobj_sp->GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
1190 }
1191 }
1192 return LLDB_INVALID_ADDRESS;
1193 };
1194
1195 // On modern apple platforms, there is a small data structure that looks
1196 // approximately like this:
1197 // struct TLS_Thunk {
1198 // void *(*get_addr)(struct TLS_Thunk *);
1199 // size_t key;
1200 // size_t offset;
1201 // }
1202 //
1203 // The strategy is to take get_addr and call it with the address of the
1204 // containing TLS_Thunk structure.
1205 //
1206 // On older apple platforms, the key is treated as a pthread_key_t and passed
1207 // to pthread_getspecific. The pointer returned from that call is added to
1208 // offset to get the relevant data block.
1209
1210 const uint32_t addr_size = m_process->GetAddressByteSize();
1211 uint8_t buf[sizeof(addr_t) * 3];
1212 Status error;
1213 const size_t tls_data_size = addr_size * 3;
1214 const size_t bytes_read = target.ReadMemory(
1215 tls_addr, buf, tls_data_size, error, /*force_live_memory = */ true);
1216 if (bytes_read != tls_data_size || error.Fail())
1217 return LLDB_INVALID_ADDRESS;
1218
1219 DataExtractor data(buf, sizeof(buf), m_process->GetByteOrder(), addr_size);
1220 lldb::offset_t offset = 0;
1221 const addr_t tls_thunk = data.GetAddress(&offset);
1222 const addr_t key = data.GetAddress(&offset);
1223 const addr_t tls_offset = data.GetAddress(&offset);
1224
1225 if (tls_thunk != 0) {
1226 const addr_t fixed_tls_thunk = m_process->FixCodeAddress(tls_thunk);
1227 Address thunk_load_addr;
1228 if (target.ResolveLoadAddress(fixed_tls_thunk, thunk_load_addr)) {
1229 const addr_t tls_load_addr = tls_addr.GetLoadAddress(&target);
1230 const addr_t tls_data = evaluate_tls_address(
1231 thunk_load_addr, llvm::ArrayRef<addr_t>(tls_load_addr));
1232 if (tls_data != LLDB_INVALID_ADDRESS)
1233 return tls_data;
1234 }
1235 }
1236
1237 if (key != 0) {
1238 // First check to see if we have already figured out the location of
1239 // TLS data for the pthread_key on a specific thread yet. If we have we
1240 // can re-use it since its location will not change unless the process
1241 // execs.
1242 const lldb::tid_t tid = thread_sp->GetID();
1243 auto tid_pos = m_tid_to_tls_map.find(tid);
1244 if (tid_pos != m_tid_to_tls_map.end()) {
1245 auto tls_pos = tid_pos->second.find(key);
1246 if (tls_pos != tid_pos->second.end()) {
1247 return tls_pos->second + tls_offset;
1248 }
1249 }
1250 Address pthread_getspecific_addr = GetPthreadSetSpecificAddress();
1251 if (pthread_getspecific_addr.IsValid()) {
1252 const addr_t tls_data = evaluate_tls_address(pthread_getspecific_addr,
1253 llvm::ArrayRef<addr_t>(key));
1254 if (tls_data != LLDB_INVALID_ADDRESS)
1255 return tls_data + tls_offset;
1256 }
1257 }
1258 return LLDB_INVALID_ADDRESS;
1259}
1260
1263 bool use_new_spi_interface = true;
1264
1265 llvm::VersionTuple version = process->GetHostOSVersion();
1266 if (!version.empty()) {
1267 using namespace llvm;
1268 const Triple::OSType os_type =
1269 process->GetTarget().GetArchitecture().GetTriple().getOS();
1270
1271 auto OlderThan = [os_type, version](llvm::Triple::OSType o,
1272 llvm::VersionTuple v) -> bool {
1273 return os_type == o && version < v;
1274 };
1275
1276 if (OlderThan(Triple::MacOSX, VersionTuple(10, 12)))
1277 use_new_spi_interface = false;
1278
1279 if (OlderThan(Triple::IOS, VersionTuple(10)))
1280 use_new_spi_interface = false;
1281
1282 if (OlderThan(Triple::TvOS, VersionTuple(10)))
1283 use_new_spi_interface = false;
1284
1285 if (OlderThan(Triple::WatchOS, VersionTuple(3)))
1286 use_new_spi_interface = false;
1287
1288 // llvm::Triple::BridgeOS and llvm::Triple::XROS always use the new
1289 // libdyld SPI interface.
1290 } else {
1291 // We could not get an OS version string, we are likely not
1292 // connected to debugserver and the packets to call the libdyld SPI
1293 // will not exist.
1294 use_new_spi_interface = false;
1295 }
1296
1297 // Corefiles cannot use the libdyld SPI to get the inferior's
1298 // binaries, we must find it through metadata or a scan
1299 // of the corefile memory.
1300 if (!process->IsLiveDebugSession())
1301 use_new_spi_interface = false;
1302
1303 if (log) {
1304 if (use_new_spi_interface)
1305 LLDB_LOGF(
1306 log, "DynamicLoaderDarwin::UseDYLDSPI: Use new DynamicLoader plugin");
1307 else
1308 LLDB_LOGF(
1309 log, "DynamicLoaderDarwin::UseDYLDSPI: Use old DynamicLoader plugin");
1310 }
1311 return use_new_spi_interface;
1312}
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:369
#define LLDB_LOGF(log,...)
Definition Log.h:376
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:392
#define LLDB_LOGV(log,...)
Definition Log.h:383
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:1035
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:457
bool SetTriple(const llvm::Triple &triple)
Architecture triple setter.
Definition ArchSpec.cpp:739
void MergeFrom(const ArchSpec &other)
Merges fields from another ArchSpec into this ArchSpec.
Definition ArchSpec.cpp:801
bool IsCompatibleMatch(const ArchSpec &rhs) const
Shorthand for IsMatch(rhs, CompatibleMatch).
Definition ArchSpec.h:509
const char * GetArchitectureName() const
Returns a static string representing the current architecture.
Definition ArchSpec.cpp:548
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.
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)
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
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:453
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:566
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:273
virtual FileSpec & GetFileSpec()
Get accessor to the object file specification.
Definition ObjectFile.h:282
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:275
A plug-in interface definition class for debugging a process.
Definition Process.h:354
Range< lldb::addr_t, lldb::addr_t > LoadRange
Definition Process.h:386
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:1240
virtual bool IsLiveDebugSession() const
Check if a process is a live debug session, or a corefile/post-mortem.
Definition Process.h:1499
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1250
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:560
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:1541
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:2352
bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr, uint32_t stop_id=SectionLoadHistory::eStopIDNow, bool allow_section_end=false)
Definition Target.cpp:3322
bool SetArchitecture(const ArchSpec &arch_spec, bool set_platform=false, bool merge=true)
Set the architecture for this target.
Definition Target.cpp:1705
lldb::ModuleSP GetExecutableModule()
Gets the module for the main executable.
Definition Target.cpp:1525
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:2004
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition Target.h:1141
const ArchSpec & GetArchitecture() const
Definition Target.h:1183
void SetExecutableModule(lldb::ModuleSP &module_sp, LoadDependentFiles load_dependent_files=eLoadDependentsDefault)
Set the main executable module.
Definition Target.cpp:1576
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:332
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