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