LLDB mainline
DynamicLoaderMacOS.cpp
Go to the documentation of this file.
1//===-- DynamicLoaderMacOS.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#include "lldb/Core/Debugger.h"
11#include "lldb/Core/Module.h"
13#include "lldb/Core/Section.h"
16#include "lldb/Target/ABI.h"
19#include "lldb/Target/Target.h"
20#include "lldb/Target/Thread.h"
22#include "lldb/Utility/Log.h"
23#include "lldb/Utility/State.h"
24
25#include "llvm/Support/Error.h"
26
27#include "DynamicLoaderDarwin.h"
28#include "DynamicLoaderMacOS.h"
29
31
32using namespace lldb;
33using namespace lldb_private;
34
35// Create an instance of this class. This function is filled into the plugin
36// info class that gets handed out by the plugin factory and allows the lldb to
37// instantiate an instance of this class.
39 bool force) {
40 bool create = force;
41 if (!create) {
42 create = true;
43 Module *exe_module = process->GetTarget().GetExecutableModulePointer();
44 if (exe_module) {
45 ObjectFile *object_file = exe_module->GetObjectFile();
46 if (object_file) {
47 create = (object_file->GetStrata() == ObjectFile::eStrataUser);
48 }
49 }
50
51 if (create) {
52 const llvm::Triple &triple_ref =
53 process->GetTarget().GetArchitecture().GetTriple();
54 switch (triple_ref.getOS()) {
55 case llvm::Triple::Darwin:
56 case llvm::Triple::MacOSX:
57 case llvm::Triple::IOS:
58 case llvm::Triple::TvOS:
59 case llvm::Triple::WatchOS:
60 case llvm::Triple::BridgeOS:
61 case llvm::Triple::DriverKit:
62 case llvm::Triple::XROS:
63 create = triple_ref.getVendor() == llvm::Triple::Apple;
64 break;
65 default:
66 create = false;
67 break;
68 }
69 }
70 }
71
72 if (!UseDYLDSPI(process)) {
73 create = false;
74 }
75
76 if (create)
77 return new DynamicLoaderMacOS(process);
78 return nullptr;
79}
80
81// Constructor
88
89// Destructor
96
98 std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
99 bool did_exec = false;
100 if (m_process) {
101 // If we are stopped after an exec, we will have only one thread...
102 if (m_process->GetThreadList().GetSize() == 1) {
103 // Maybe we still have an image infos address around? If so see
104 // if that has changed, and if so we have exec'ed.
106 lldb::addr_t image_infos_address = m_process->GetImageInfoAddress();
107 if (image_infos_address != m_maybe_image_infos_address) {
108 // We don't really have to reset this here, since we are going to
109 // call DoInitialImageFetch right away to handle the exec. But in
110 // case anybody looks at it in the meantime, it can't hurt.
111 m_maybe_image_infos_address = image_infos_address;
112 did_exec = true;
113 }
114 }
115
116 if (!did_exec) {
117 // See if we are stopped at '_dyld_start'
118 ThreadSP thread_sp(m_process->GetThreadList().GetThreadAtIndex(0));
119 if (thread_sp) {
120 lldb::StackFrameSP frame_sp(thread_sp->GetStackFrameAtIndex(0));
121 if (frame_sp) {
122 const Symbol *symbol =
123 frame_sp->GetSymbolContext(eSymbolContextSymbol).symbol;
124 if (symbol) {
125 if (symbol->GetName() == "_dyld_start")
126 did_exec = true;
127 }
128 }
129 }
130 }
131 }
132 }
133
134 if (did_exec) {
138 }
139 return did_exec;
140}
141
142// Clear out the state of this class.
144 std::lock_guard<std::recursive_mutex> guard(m_mutex);
145
147 m_process->GetTarget().RemoveBreakpointByID(m_break_id);
149 m_process->GetTarget().RemoveBreakpointByID(m_dyld_handover_break_id);
150
154}
155
158 return true;
159
160 StructuredData::ObjectSP process_state_sp(
161 m_process->GetDynamicLoaderProcessState());
162 if (!process_state_sp)
163 return true;
164 if (process_state_sp->GetAsDictionary()->HasKey("error"))
165 return true;
166 if (!process_state_sp->GetAsDictionary()->HasKey("process_state string"))
167 return true;
168 std::string proc_state = process_state_sp->GetAsDictionary()
169 ->GetValueForKey("process_state string")
170 ->GetAsString()
171 ->GetValue()
172 .str();
173 if (proc_state == "dyld_process_state_not_started" ||
174 proc_state == "dyld_process_state_dyld_initialized" ||
175 proc_state == "dyld_process_state_terminated_before_inits") {
176 return false;
177 }
179 return true;
180}
181
182// Check if we have found DYLD yet
186
193
196
197 // Remove any binaries we pre-loaded in the Target before
198 // launching/attaching. If the same binaries are present in the process,
199 // we'll get them from the shared module cache, we won't need to re-load them
200 // from disk.
202
203 StructuredData::ObjectSP all_image_info_json_sp(
204 m_process->GetLoadedDynamicLibrariesInfos(
206 ImageInfo::collection image_infos;
207 if (all_image_info_json_sp.get() &&
208 all_image_info_json_sp->GetAsDictionary() &&
209 all_image_info_json_sp->GetAsDictionary()->HasKey("images") &&
210 all_image_info_json_sp->GetAsDictionary()
211 ->GetValueForKey("images")
212 ->GetAsArray()) {
213
214 // Older debugserver (pre-2024-ish) will not recognize the
215 // eBinaryInformationLevelAddrOnly enum above, and
216 // will return the full binary information including mach
217 // header and segments/load commands. The response includes
218 // the full information on all binaries.
219 StructuredData::Array *images = all_image_info_json_sp->GetAsDictionary()
220 ->GetValueForKey("images")
221 ->GetAsArray();
222 if (images->GetSize() > 0 && images->GetItemAtIndex(0)->GetAsDictionary() &&
223 images->GetItemAtIndex(0)->GetAsDictionary()->HasKey("mach_header")) {
224 if (JSONImageInformationIntoImageInfo(all_image_info_json_sp,
225 image_infos)) {
226 LLDB_LOGF(log, "Initial module fetch: Adding %" PRIu64 " modules.\n",
227 (uint64_t)image_infos.size());
228
229 auto new_images = PreloadModulesFromImageInfos(image_infos);
232 }
233 } else {
234 // This is a newer debugserver which only replied with
235 // `load_address` for all binaries loaded in the process.
236 // We can request detailed information in smaller chunks,
237 // instead of one gigantic packet.
238 size_t image_count = images->GetSize();
239 std::vector<addr_t> load_addresses;
240 for (size_t i = 0; i < image_count; i++) {
242 images->GetItemAtIndex(i)->GetAsDictionary();
243 if (image && image->HasKey("load_address")) {
244 addr_t val = image->GetValueForKey("load_address")
245 ->GetUnsignedIntegerValue(LLDB_INVALID_ADDRESS);
246 if (val != LLDB_INVALID_ADDRESS)
247 load_addresses.push_back(val);
248 }
249 }
250 AddBinaries(load_addresses, /*expedited_binary_infos=*/{});
251 }
252 }
253
255 m_maybe_image_infos_address = m_process->GetImageInfoAddress();
256}
257
259
260// Static callback function that gets called when our DYLD notification
261// breakpoint gets hit. We update all of our image infos and then let our super
262// class DynamicLoader class decide if we should stop or not (based on global
263// preference).
266 lldb::user_id_t break_id,
267 lldb::user_id_t break_loc_id) {
268 //
269 // Our breakpoint on
270 //
271 // void lldb_image_notifier(enum dyld_image_mode mode, uint32_t infoCount,
272 // const dyld_image_info info[])
273 //
274 // has been hit. We need to read the arguments.
275
276 DynamicLoaderMacOS *dyld_instance = (DynamicLoaderMacOS *)baton;
277
278 ExecutionContext exe_ctx(context->exe_ctx_ref);
279 Process *process = exe_ctx.GetProcessPtr();
280
281 // This is a sanity check just in case this dyld_instance is an old dyld
282 // plugin's breakpoint still lying around.
283 if (process != dyld_instance->m_process)
284 return false;
285
286 if (dyld_instance->m_image_infos_stop_id != UINT32_MAX &&
287 process->GetStopID() < dyld_instance->m_image_infos_stop_id) {
288 return false;
289 }
290
291 const lldb::ABISP &abi = process->GetABI();
292 if (abi) {
293 // Build up the value array to store the three arguments given above, then
294 // get the values from the ABI:
295
296 TypeSystemClangSP scratch_ts_sp =
298 if (!scratch_ts_sp)
299 return false;
300
301 ValueList argument_values;
302
303 Value mode_value; // enum dyld_notify_mode { dyld_notify_adding=0,
304 // dyld_notify_removing=1, dyld_notify_remove_all=2,
305 // dyld_notify_dyld_moved=3 };
306 Value count_value; // uint32_t
307 Value headers_value; // struct dyld_image_info machHeaders[]
308
309 CompilerType clang_void_ptr_type =
310 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
311 CompilerType clang_uint32_type =
312 scratch_ts_sp->GetBuiltinTypeForEncodingAndBitSize(lldb::eEncodingUint,
313 32);
314 CompilerType clang_uint64_type =
315 scratch_ts_sp->GetBuiltinTypeForEncodingAndBitSize(lldb::eEncodingUint,
316 32);
317
319 mode_value.SetCompilerType(clang_uint32_type);
320
322 count_value.SetCompilerType(clang_uint32_type);
323
325 headers_value.SetCompilerType(clang_void_ptr_type);
326
327 argument_values.PushValue(mode_value);
328 argument_values.PushValue(count_value);
329 argument_values.PushValue(headers_value);
330
331 Thread &thread = exe_ctx.GetThreadRef();
332 if (abi->GetArgumentValues(thread, argument_values)) {
333 uint32_t dyld_mode =
334 argument_values.GetValueAtIndex(0)->GetScalar().UInt(-1);
335 if (dyld_mode != static_cast<uint32_t>(-1)) {
336 // Okay the mode was right, now get the number of elements, and the
337 // array of new elements...
338 uint32_t image_infos_count =
339 argument_values.GetValueAtIndex(1)->GetScalar().UInt(-1);
340 if (image_infos_count != static_cast<uint32_t>(-1)) {
341 addr_t header_array =
342 argument_values.GetValueAtIndex(2)->GetScalar().ULongLong(-1);
343 if (header_array != static_cast<uint64_t>(-1)) {
344 std::vector<addr_t> image_load_addresses;
345 // header_array points to an array of image_infos_count elements,
346 // each is
347 // struct dyld_image_info {
348 // const struct mach_header* imageLoadAddress;
349 // const char* imageFilePath;
350 // uintptr_t imageFileModDate;
351 // };
352 //
353 // and we only need the imageLoadAddress fields.
354
355 // The remote stub may have provided the addresses in the
356 // stop packet already.
357 image_load_addresses = thread.FetchNewlyAddedBinaries();
358 // Or, read them from memory.
359 if (image_load_addresses.size() != image_infos_count) {
360 image_load_addresses.clear();
361 ArchSpec target_arch = process->GetTarget().GetArchitecture();
362 const int addrsize = target_arch.GetAddressByteSize();
363 // Read the entire block of memory that we'll need to
364 // iterate over in one large read, to minimize packets sent.
365 WritableDataBufferSP buffer_sp = std::make_shared<DataBufferHeap>(
366 addrsize * 3 * image_infos_count, 0);
367 Status read_error;
368 if (process->ReadMemory(header_array, buffer_sp->GetBytes(),
369 buffer_sp->GetByteSize(),
370 read_error) == buffer_sp->GetByteSize() &&
371 read_error.Success()) {
372 DataExtractor added_binaries(
373 buffer_sp, target_arch.GetByteOrder(), addrsize);
374
375 offset_t offset = 0;
376 for (uint64_t i = 0; i < image_infos_count; i++) {
377 addr_t addr = added_binaries.GetAddress(&offset);
378 image_load_addresses.push_back(addr);
379 offset += 2 * addrsize;
380 }
381 }
382 if (!read_error.Success())
384 "DynamicLoaderMacOS::NotifyBreakpointHit unable "
385 "to read binary mach-o load address at 0x%" PRIx64,
386 header_array);
387 }
388 if (dyld_mode == 0) {
389 // dyld_notify_adding
390 if (process->GetTarget().GetImages().GetSize() == 0) {
391 // When all images have been removed, we're doing the
392 // dyld handover from a launch-dyld to a shared-cache-dyld,
393 // and we've just hit our one-shot address breakpoint in
394 // the sc-dyld. Note that the image addresses passed to
395 // this function are inferior sizeof(void*) not uint64_t's
396 // like our normal notification, so don't even look at
397 // image_load_addresses.
398
399 dyld_instance->ClearDYLDHandoverBreakpoint();
400
401 dyld_instance->DoInitialImageFetch();
402 dyld_instance->SetNotificationBreakpoint();
403 } else {
404 dyld_instance->AddBinaries(image_load_addresses,
405 thread.FetchDetailedBinariesInfo());
406 }
407 } else if (dyld_mode == 1) {
408 // dyld_notify_removing
409 dyld_instance->UnloadImages(image_load_addresses);
410 } else if (dyld_mode == 2) {
411 // dyld_notify_remove_all
412 dyld_instance->UnloadAllImages();
413 } else if (dyld_mode == 3 && image_infos_count == 1) {
414 // dyld_image_dyld_moved
415
416 dyld_instance->ClearNotificationBreakpoint();
417 dyld_instance->UnloadAllImages();
418 dyld_instance->ClearDYLDModule();
419 process->GetTarget().GetImages().Clear();
420 process->GetTarget().ClearSectionLoadList();
421
422 addr_t all_image_infos = process->GetImageInfoAddress();
423 int addr_size =
425 addr_t notification_location = all_image_infos + 4 + // version
426 4 + // infoArrayCount
427 addr_size; // infoArray
428 llvm::Expected<lldb::addr_t> notification_addr =
429 process->ReadPointerFromMemory(notification_location);
430 if (!notification_addr) {
431 llvm::consumeError(notification_addr.takeError());
433 "DynamicLoaderMacOS::NotifyBreakpointHit unable "
434 "to read address of dyld-handover notification function at "
435 "0x%" PRIx64,
436 notification_location);
437 } else {
438 dyld_instance->SetDYLDHandoverBreakpoint(
439 process->FixCodeAddress(*notification_addr));
440 }
441 }
442 }
443 }
444 }
445 }
446 } else {
447 Target &target = process->GetTarget();
449 "no ABI plugin located for triple " +
450 target.GetArchitecture().GetTriple().getTriple() +
451 ": shared libraries will not be registered",
452 target.GetDebugger().GetID());
453 }
454
455 // Return true to stop the target, false to just let the target run
456 return dyld_instance->GetStopWhenImagesChange();
457}
458
459static size_t LibraryInfosCount(StructuredData::ObjectSP binaries_info_sp) {
460 if (!binaries_info_sp)
461 return 0;
462 if (StructuredData::Dictionary *dict = binaries_info_sp->GetAsDictionary()) {
463 if (!dict->HasKey("images"))
464 return 0;
465 if (StructuredData::Array *images =
466 dict->GetValueForKey("images")->GetAsArray())
467 return images->GetSize();
468 }
469
470 return 0;
471}
472
474 const std::vector<lldb::addr_t> &load_addresses,
475 StructuredData::ObjectSP expedited_binary_infos) {
477 ImageInfo::collection image_infos;
478 if (load_addresses.empty())
479 return;
480
481 // If the expedited detailed binaries information covers
482 // all of the newly added binaries, use that info and
483 // return.
484 if (LibraryInfosCount(expedited_binary_infos) == load_addresses.size() &&
485 JSONImageInformationIntoImageInfo(expedited_binary_infos, image_infos)) {
486 auto new_images = PreloadModulesFromImageInfos(image_infos);
490 return;
491 }
492
493 // For now, hardcode a limit of fetching 600 binaries at once.
494 // Fetching the full binary information for a large number of
495 // binaries can cause debugserver to use too much memory on
496 // memory-limited environments, and get killed.
497 const size_t image_fetch_max = 600;
498 size_t fetched = 0;
499 size_t total_image_size = load_addresses.size();
500 while (fetched < total_image_size) {
501 size_t this_fetch_amt =
502 std::min(image_fetch_max, total_image_size - fetched);
503 std::vector<addr_t> fetch_binaries(load_addresses.begin() + fetched,
504 load_addresses.begin() + fetched +
505 this_fetch_amt);
506
507 LLDB_LOGF(log, "Adding %" PRId64 " modules.",
508 (uint64_t)fetch_binaries.size());
509 image_infos.clear();
510 StructuredData::ObjectSP binaries_info_sp =
511 m_process->GetLoadedDynamicLibrariesInfos(eBinaryInformationLevelFull,
512 fetch_binaries);
513 if (LibraryInfosCount(binaries_info_sp) == fetch_binaries.size()) {
514 if (JSONImageInformationIntoImageInfo(binaries_info_sp, image_infos)) {
515 auto new_images = PreloadModulesFromImageInfos(image_infos);
518 }
519 }
520 fetched += this_fetch_amt;
521 }
523}
524
525// Dump the _dyld_all_image_infos members and all current image infos that we
526// have parsed to the file handle provided.
528 if (log == nullptr)
529 return;
530}
531
532// Look in dyld's dyld_all_image_infos structure for the address
533// of the notification function.
534// We can find the address of dyld_all_image_infos by a system
535// call, even if we don't have a dyld binary registered in lldb's
536// image list.
537// At process launch time - before dyld has executed any instructions -
538// the address of the notification function is not a resolved vm address
539// yet. dyld_all_image_infos also has a field with its own address
540// in it, and this will also be unresolved when we're at this state.
541// So we can compare the address of the object with this field and if
542// they differ, dyld hasn't started executing yet and we can't get the
543// notification address this way.
545 addr_t notification_addr = LLDB_INVALID_ADDRESS;
546 if (!m_process)
547 return notification_addr;
548
549 addr_t all_image_infos_addr = m_process->GetImageInfoAddress();
550 if (all_image_infos_addr == LLDB_INVALID_ADDRESS)
551 return notification_addr;
552
553 const uint32_t addr_size =
554 m_process->GetTarget().GetArchitecture().GetAddressByteSize();
555 offset_t registered_infos_addr_offset =
556 sizeof(uint32_t) + // version
557 sizeof(uint32_t) + // infoArrayCount
558 addr_size + // infoArray
559 addr_size + // notification
560 addr_size + // processDetachedFromSharedRegion +
561 // libSystemInitialized + pad
562 addr_size + // dyldImageLoadAddress
563 addr_size + // jitInfo
564 addr_size + // dyldVersion
565 addr_size + // errorMessage
566 addr_size + // terminationFlags
567 addr_size + // coreSymbolicationShmPage
568 addr_size + // systemOrderFlag
569 addr_size + // uuidArrayCount
570 addr_size; // uuidArray
571 // dyldAllImageInfosAddress
572
573 // If the dyldAllImageInfosAddress does not match
574 // the actual address of this struct, dyld has not started
575 // executing yet. The 'notification' field can't be used by
576 // lldb until it's resolved to an actual address.
577 llvm::Expected<lldb::addr_t> registered_infos_addr =
578 m_process->ReadPointerFromMemory(all_image_infos_addr +
579 registered_infos_addr_offset);
580 if (!registered_infos_addr) {
581 llvm::consumeError(registered_infos_addr.takeError());
582 return notification_addr;
583 }
584 if (*registered_infos_addr != all_image_infos_addr)
585 return notification_addr;
586
587 offset_t notification_fptr_offset = sizeof(uint32_t) + // version
588 sizeof(uint32_t) + // infoArrayCount
589 addr_size; // infoArray
590
591 llvm::Expected<lldb::addr_t> notification_fptr =
592 m_process->ReadPointerFromMemory(all_image_infos_addr +
593 notification_fptr_offset);
594 if (notification_fptr)
595 notification_addr = m_process->FixCodeAddress(*notification_fptr);
596 else
597 llvm::consumeError(notification_fptr.takeError());
598 return notification_addr;
599}
600
601// We want to put a breakpoint on dyld's lldb_image_notifier()
602// but we may have attached to the process during the
603// transition from on-disk-dyld to shared-cache-dyld, so there's
604// officially no dyld binary loaded in the process (libdyld will
605// report none when asked), but the kernel can find the dyld_all_image_infos
606// struct and the function pointer for lldb_image_notifier is in
607// that struct.
609
610 // First try to find the notification breakpoint function by name
612 ModuleSP dyld_sp(GetDYLDModule());
613 if (dyld_sp) {
614 bool internal = true;
615 bool hardware = false;
616 LazyBool skip_prologue = eLazyBoolNo;
617 FileSpecList *source_files = nullptr;
618 FileSpecList dyld_filelist;
619 dyld_filelist.Append(dyld_sp->GetFileSpec());
620
621 Breakpoint *breakpoint =
622 m_process->GetTarget()
623 .CreateBreakpoint(&dyld_filelist, source_files,
624 "lldb_image_notifier", eFunctionNameTypeFull,
625 eLanguageTypeUnknown, 0, false, skip_prologue,
626 internal, hardware)
627 .get();
629 true);
630 breakpoint->SetBreakpointKind("shared-library-event");
631 if (breakpoint->HasResolvedLocations())
632 m_break_id = breakpoint->GetID();
633 else
634 m_process->GetTarget().RemoveBreakpointByID(breakpoint->GetID());
635
637 Breakpoint *breakpoint =
638 m_process->GetTarget()
639 .CreateBreakpoint(&dyld_filelist, source_files,
640 "gdb_image_notifier", eFunctionNameTypeFull,
642 /*offset_is_insn_count = */ false,
643 skip_prologue, internal, hardware)
644 .get();
646 true);
647 breakpoint->SetBreakpointKind("shared-library-event");
648 if (breakpoint->HasResolvedLocations())
649 m_break_id = breakpoint->GetID();
650 else
651 m_process->GetTarget().RemoveBreakpointByID(breakpoint->GetID());
652 }
653 }
654 }
655
656 // Failing that, find dyld_all_image_infos struct in memory,
657 // read the notification function pointer at the offset.
659 addr_t notification_addr = GetNotificationFuncAddrFromImageInfos();
660 if (notification_addr != LLDB_INVALID_ADDRESS) {
661 Address so_addr;
662 // We may not have a dyld binary mapped to this address yet;
663 // don't try to express the Address object as section+offset,
664 // only as a raw load address.
665 so_addr.SetRawAddress(notification_addr);
666 Breakpoint *dyld_break =
667 m_process->GetTarget().CreateBreakpoint(so_addr, true, false).get();
669 true);
670 dyld_break->SetBreakpointKind("shared-library-event");
671 if (dyld_break->HasResolvedLocations())
672 m_break_id = dyld_break->GetID();
673 else
674 m_process->GetTarget().RemoveBreakpointByID(dyld_break->GetID());
675 }
676 }
678}
679
681 addr_t notification_address) {
683 BreakpointSP dyld_handover_bp = m_process->GetTarget().CreateBreakpoint(
684 notification_address, true, false);
685 dyld_handover_bp->SetCallback(DynamicLoaderMacOS::NotifyBreakpointHit, this,
686 true);
687 dyld_handover_bp->SetOneShot(true);
688 m_dyld_handover_break_id = dyld_handover_bp->GetID();
689 return true;
690 }
691 return false;
692}
693
699
700addr_t
702 SymbolContext sc;
703 Target &target = m_process->GetTarget();
704 if (Symtab *symtab = module->GetSymtab()) {
705 std::vector<uint32_t> match_indexes;
706 ConstString g_symbol_name("_dyld_global_lock_held");
707 uint32_t num_matches = 0;
708 num_matches =
709 symtab->AppendSymbolIndexesWithName(g_symbol_name, match_indexes);
710 if (num_matches == 1) {
711 const Symbol *symbol = symtab->SymbolAtIndex(match_indexes[0]);
712 if (symbol &&
713 (symbol->ValueIsAddress() || symbol->GetAddressRef().IsValid())) {
714 return symbol->GetAddressRef().GetOpcodeLoadAddress(&target);
715 }
716 }
717 }
719}
720
721// Look for this symbol:
722//
723// int __attribute__((visibility("hidden"))) _dyld_global_lock_held =
724// 0;
725//
726// in libdyld.dylib.
729 addr_t symbol_address = LLDB_INVALID_ADDRESS;
730 ConstString g_libdyld_name("libdyld.dylib");
731 Target &target = m_process->GetTarget();
732 const ModuleList &target_modules = target.GetImages();
733 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
734
735 // Find any modules named "libdyld.dylib" and look for the symbol there first
736 for (ModuleSP module_sp : target.GetImages().ModulesNoLocking()) {
737 if (module_sp) {
738 if (module_sp->GetFileSpec().GetFilename() == g_libdyld_name) {
739 symbol_address = GetDyldLockVariableAddressFromModule(module_sp.get());
740 if (symbol_address != LLDB_INVALID_ADDRESS)
741 break;
742 }
743 }
744 }
745
746 // Search through all modules looking for the symbol in them
747 if (symbol_address == LLDB_INVALID_ADDRESS) {
748 for (ModuleSP module_sp : target.GetImages().Modules()) {
749 if (module_sp) {
750 addr_t symbol_address =
752 if (symbol_address != LLDB_INVALID_ADDRESS)
753 break;
754 }
755 }
756 }
757
758 // Default assumption is that it is OK to load images. Only say that we
759 // cannot load images if we find the symbol in libdyld and it indicates that
760 // we cannot.
761
762 if (symbol_address != LLDB_INVALID_ADDRESS) {
763 {
764 int lock_held =
765 m_process->ReadUnsignedIntegerFromMemory(symbol_address, 4, 0, error);
766 if (lock_held != 0) {
767 error =
768 Status::FromErrorString("dyld lock held - unsafe to load images.");
769 }
770 }
771 } else {
772 // If we were unable to find _dyld_global_lock_held in any modules, or it
773 // is not loaded into memory yet, we may be at process startup (sitting at
774 // _dyld_start) - so we should not allow dlopen calls. But if we found more
775 // than one module then we are clearly past _dyld_start so in that case
776 // we'll default to "it's safe".
777 if (target.GetImages().GetSize() <= 1)
778 error = Status::FromErrorString("could not find the dyld library or "
779 "the dyld lock symbol");
780 }
781 return error;
782}
783
785 lldb::addr_t &base_address, UUID &uuid, LazyBool &using_shared_cache,
786 LazyBool &private_shared_cache, FileSpec &shared_cache_path,
787 std::optional<uint64_t> &size) {
788 base_address = LLDB_INVALID_ADDRESS;
789 uuid.Clear();
790 using_shared_cache = eLazyBoolCalculate;
791 private_shared_cache = eLazyBoolCalculate;
792 size.reset();
793
794 if (m_process) {
795 StructuredData::ObjectSP info = m_process->GetSharedCacheInfo();
796 StructuredData::Dictionary *info_dict = nullptr;
797 if (info.get() && info->GetAsDictionary()) {
798 info_dict = info->GetAsDictionary();
799 }
800
801 // { "shared_cache_base_address":6580879360,
802 // "shared_cache_uuid":"71E62C65-D8D9-32D0-9A0B-7F5154C8049F",
803 // "no_shared_cache":false,
804 // "shared_cache_private_cache":false,
805 // "shared_cache_path":"/S/V/P/C/OS/Sm/L/dyld/dyld_shared_cache_arm64e",
806 // "shared_cache_size":6012010496
807 // }
808
809 if (info_dict && info_dict->HasKey("shared_cache_uuid") &&
810 info_dict->HasKey("no_shared_cache") &&
811 info_dict->HasKey("shared_cache_private_cache") &&
812 info_dict->HasKey("shared_cache_base_address")) {
813 base_address = info_dict->GetValueForKey("shared_cache_base_address")
814 ->GetUnsignedIntegerValue(LLDB_INVALID_ADDRESS);
815 std::string uuid_str = std::string(
816 info_dict->GetValueForKey("shared_cache_uuid")->GetStringValue());
817 if (!uuid_str.empty())
818 uuid.SetFromStringRef(uuid_str);
819 if (!info_dict->GetValueForKey("no_shared_cache")->GetBooleanValue())
820 using_shared_cache = eLazyBoolYes;
821 else
822 using_shared_cache = eLazyBoolNo;
823 if (info_dict->GetValueForKey("shared_cache_private_cache")
824 ->GetBooleanValue())
825 private_shared_cache = eLazyBoolYes;
826 else
827 private_shared_cache = eLazyBoolNo;
828 if (info_dict->HasKey("shared_cache_path")) {
829 llvm::StringRef filepath =
830 info_dict->GetValueForKey("shared_cache_path")->GetStringValue();
831 shared_cache_path.SetPath(filepath);
832 }
833 if (info_dict->HasKey("shared_cache_size")) {
834 uint64_t val = info_dict->GetValueForKey("shared_cache_size")
835 ->GetUnsignedIntegerValue(LLDB_INVALID_ADDRESS);
836 if (val != LLDB_INVALID_ADDRESS)
837 size = val;
838 }
839 return true;
840 }
841 }
842 return false;
843}
844
849
853
855 return "Dynamic loader plug-in that watches for shared library loads/unloads "
856 "in MacOSX user processes.";
857}
static llvm::raw_ostream & error(Stream &strm)
static size_t LibraryInfosCount(StructuredData::ObjectSP binaries_info_sp)
#define LLDB_LOGF(log,...)
Definition Log.h:389
bool SetNotificationBreakpoint() override
static lldb_private::DynamicLoader * CreateInstance(lldb_private::Process *process, bool force)
lldb_private::Status CanLoadImage() override
Ask if it is ok to try and load or unload an shared library (image).
void PutToLog(lldb_private::Log *log) const
bool IsFullyInitialized() override
Return whether the dynamic loader is fully initialized and it's safe to call its APIs.
lldb::addr_t GetDyldLockVariableAddressFromModule(lldb_private::Module *module)
bool NeedToDoInitialImageFetch() override
std::recursive_mutex m_mutex
void DoInitialImageFetch() override
static llvm::StringRef GetPluginNameStatic()
static llvm::StringRef GetPluginDescriptionStatic()
bool GetSharedCacheInformation(lldb::addr_t &base_address, lldb_private::UUID &uuid, lldb_private::LazyBool &using_shared_cache, lldb_private::LazyBool &private_shared_cache, lldb_private::FileSpec &shared_cache_path, std::optional< uint64_t > &size) override
Get information about the shared cache for a process, if possible.
lldb::user_id_t m_break_id
lldb::addr_t GetNotificationFuncAddrFromImageInfos()
bool SetDYLDHandoverBreakpoint(lldb::addr_t notification_address)
void ClearNotificationBreakpoint() override
void AddBinaries(const std::vector< lldb::addr_t > &load_addresses, lldb_private::StructuredData::ObjectSP expedited_binary_infos)
static bool NotifyBreakpointHit(void *baton, lldb_private::StoppointCallbackContext *context, lldb::user_id_t break_id, lldb::user_id_t break_loc_id)
lldb::addr_t m_maybe_image_infos_address
bool ProcessDidExec() override
Called after attaching a process.
lldb::user_id_t m_dyld_handover_break_id
DynamicLoaderMacOS(lldb_private::Process *process)
bool DidSetNotificationBreakpoint() override
A section + offset based address class.
Definition Address.h:62
lldb::addr_t GetOpcodeLoadAddress(Target *target, AddressClass addr_class=AddressClass::eInvalid) const
Get the load address as an opcode load address.
Definition Address.cpp:360
void SetRawAddress(lldb::addr_t addr)
Definition Address.h:441
bool IsValid() const
Check if the object state is valid.
Definition Address.h:355
An architecture specification class.
Definition ArchSpec.h:32
uint32_t GetAddressByteSize() const
Returns the size in bytes of an address of the current architecture.
Definition ArchSpec.cpp:891
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:545
lldb::ByteOrder GetByteOrder() const
Returns the byte order for the architecture specification.
Definition ArchSpec.cpp:940
General Outline: A breakpoint has four main parts, a filter, a resolver, the list of breakpoint locat...
Definition Breakpoint.h:83
void SetBreakpointKind(const char *kind)
Set the "kind" description for a breakpoint.
Definition Breakpoint.h:484
bool HasResolvedLocations() const
Return whether this breakpoint has any resolved locations.
void SetCallback(BreakpointHitCallback callback, void *baton, bool is_synchronous=false)
Set the callback action invoked when the breakpoint is hit.
Generic representation of a type in a programming language.
A uniqued constant string class.
Definition ConstString.h:40
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.
DynamicLoaderDarwin(lldb_private::Process *process)
std::recursive_mutex & GetMutex() const
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)
void UpdateSpecialBinariesFromPreloadedModules(std::vector< std::pair< ImageInfo, lldb::ModuleSP > > &images)
bool AddModulesUsingPreloadedModules(std::vector< std::pair< ImageInfo, lldb::ModuleSP > > &images)
static bool UseDYLDSPI(lldb_private::Process *process)
lldb_private::Address m_pthread_getspecific_addr
void UnloadImages(const std::vector< lldb::addr_t > &solib_addresses)
Process * m_process
The process that this dynamic loader plug-in is tracking.
bool GetStopWhenImagesChange() const
Get whether the process should stop when images change.
DynamicLoader(Process *process)
Construct with a process.
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
Process * GetProcessPtr() const
Returns a pointer to the process object.
Thread & GetThreadRef() const
Returns a reference to the thread object.
A file collection class.
void Append(const FileSpec &file)
Append a FileSpec object to the list.
A file utility class.
Definition FileSpec.h:56
void SetPath(llvm::StringRef p)
Temporary helper for FileSystem change.
Definition FileSpec.h:286
A collection class for Module objects.
Definition ModuleList.h:125
ModuleIterableNoLocking ModulesNoLocking() const
Definition ModuleList.h:577
std::recursive_mutex & GetMutex() const
Definition ModuleList.h:252
void Clear()
Clear the object's state.
ModuleIterable Modules() const
Definition ModuleList.h:571
size_t GetSize() const
Gets the size of the module list.
A class that describes an executable image and its associated object and symbol files.
Definition Module.h:91
virtual ObjectFile * GetObjectFile()
Get the object file representation for the current architecture.
Definition Module.cpp:1179
Symtab * GetSymtab(bool can_create=true)
Get the module's symbol table.
Definition Module.cpp:1002
A plug-in interface definition class for object file parsers.
Definition ObjectFile.h:46
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
A plug-in interface definition class for debugging a process.
Definition Process.h:367
virtual size_t ReadMemory(const ProcessAddress &process_addr, void *buf, size_t size, Status &error)
Read of memory from a process.
Definition Process.cpp:2081
llvm::Expected< lldb::addr_t > ReadPointerFromMemory(lldb::addr_t vm_addr)
Definition Process.cpp:2561
virtual lldb::addr_t GetImageInfoAddress()
Get the image information address for the current process.
Definition Process.cpp:1504
lldb::addr_t FixCodeAddress(lldb::addr_t pc)
Some targets might use bits in a code address to indicate a mode switch, ARM uses bit zero to signify...
Definition Process.cpp:6274
uint32_t GetStopID() const
Definition Process.h:1513
const lldb::ABISP & GetABI()
Definition Process.cpp:1506
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1266
unsigned int UInt(unsigned int fail_value=0) const
Definition Scalar.cpp:352
unsigned long long ULongLong(unsigned long long fail_value=0) const
Definition Scalar.cpp:366
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.
An error handling class.
Definition Status.h:118
static Status FromErrorString(const char *str)
Definition Status.h:141
bool Success() const
Test for success condition.
Definition Status.cpp:303
General Outline: When we hit a breakpoint we need to package up whatever information is needed to eva...
lldb::break_id_t GetID() const
Definition Stoppoint.cpp:22
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 symbol context baton that can be handed other debug core functions.
bool ValueIsAddress() const
Definition Symbol.cpp:191
Address & GetAddressRef()
Definition Symbol.h:78
ConstString GetName() const
Definition Symbol.cpp:612
Module * GetExecutableModulePointer()
Definition Target.cpp:1641
Debugger & GetDebugger() const
Definition Target.h:1337
void ClearSectionLoadList()
Definition Target.cpp:6052
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition Target.h:1254
const ArchSpec & GetArchitecture() const
Definition Target.h:1296
Represents UUID's of various sizes.
Definition UUID.h:27
bool SetFromStringRef(llvm::StringRef str)
Definition UUID.cpp:101
void Clear()
Definition UUID.h:62
void PushValue(const Value &value)
Definition Value.cpp:698
Value * GetValueAtIndex(size_t idx)
Definition Value.cpp:702
const Scalar & GetScalar() const
See comment on m_scalar to understand what GetScalar returns.
Definition Value.h:114
@ Scalar
A raw scalar value.
Definition Value.h:46
void SetCompilerType(const CompilerType &compiler_type)
Definition Value.cpp:276
void SetValueType(ValueType value_type)
Definition Value.h:90
#define LLDB_INVALID_BREAK_ID
#define LLDB_BREAK_ID_IS_VALID(bid)
#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
std::shared_ptr< lldb_private::ABI > ABISP
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::shared_ptr< lldb_private::Thread > ThreadSP
uint64_t offset_t
Definition lldb-types.h:86
@ eLanguageTypeUnknown
Unknown or invalid language value.
std::shared_ptr< lldb_private::Breakpoint > BreakpointSP
@ eEncodingUint
unsigned integer
std::shared_ptr< lldb_private::TypeSystemClang > TypeSystemClangSP
uint64_t user_id_t
Definition lldb-types.h:83
std::shared_ptr< lldb_private::WritableDataBuffer > WritableDataBufferSP
uint64_t addr_t
Definition lldb-types.h:80
@ eBinaryInformationLevelFull
@ eBinaryInformationLevelAddrOnly
std::shared_ptr< lldb_private::Module > ModuleSP
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition UserID.h:47