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
9#include "lldb/Breakpoint/StoppointCallbackContext.h"
10#include "lldb/Core/Debugger.h"
11#include "lldb/Core/Module.h"
12#include "lldb/Core/PluginManager.h"
13#include "lldb/Core/Section.h"
14#include "lldb/Symbol/ObjectFile.h"
15#include "lldb/Symbol/SymbolVendor.h"
16#include "lldb/Target/ABI.h"
17#include "lldb/Target/SectionLoadList.h"
18#include "lldb/Target/StackFrame.h"
19#include "lldb/Target/Target.h"
20#include "lldb/Target/Thread.h"
21#include "lldb/Utility/LLDBLog.h"
22#include "lldb/Utility/Log.h"
23#include "lldb/Utility/State.h"
24
25#include "DynamicLoaderDarwin.h"
26#include "DynamicLoaderMacOS.h"
27
28#include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
29
30using namespace lldb;
31using namespace lldb_private;
32
33// Create an instance of this class. This function is filled into the plugin
34// info class that gets handed out by the plugin factory and allows the lldb to
35// instantiate an instance of this class.
36DynamicLoader *DynamicLoaderMacOS::CreateInstance(Process *process,
37 bool force) {
38 bool create = force;
39 if (!create) {
40 create = true;
41 Module *exe_module = process->GetTarget().GetExecutableModulePointer();
42 if (exe_module) {
43 ObjectFile *object_file = exe_module->GetObjectFile();
44 if (object_file) {
45 create = (object_file->GetStrata() == ObjectFile::eStrataUser);
46 }
47 }
48
49 if (create) {
50 const llvm::Triple &triple_ref =
51 process->GetTarget().GetArchitecture().GetTriple();
52 switch (triple_ref.getOS()) {
53 case llvm::Triple::Darwin:
54 case llvm::Triple::MacOSX:
55 case llvm::Triple::IOS:
56 case llvm::Triple::TvOS:
57 case llvm::Triple::WatchOS:
58 case llvm::Triple::XROS:
59 case llvm::Triple::BridgeOS:
60 create = triple_ref.getVendor() == llvm::Triple::Apple;
61 break;
62 default:
63 create = false;
64 break;
65 }
66 }
67 }
68
69 if (!UseDYLDSPI(process)) {
70 create = false;
71 }
72
73 if (create)
74 return new DynamicLoaderMacOS(process);
75 return nullptr;
76}
77
78// Constructor
79DynamicLoaderMacOS::DynamicLoaderMacOS(Process *process)
80 : DynamicLoaderDarwin(process), m_image_infos_stop_id(UINT32_MAX),
81 m_break_id(LLDB_INVALID_BREAK_ID),
82 m_dyld_handover_break_id(LLDB_INVALID_BREAK_ID), m_mutex(),
83 m_maybe_image_infos_address(LLDB_INVALID_ADDRESS),
84 m_libsystem_fully_initalized(false) {}
85
86// Destructor
87DynamicLoaderMacOS::~DynamicLoaderMacOS() {
88 if (LLDB_BREAK_ID_IS_VALID(m_break_id))
89 m_process->GetTarget().RemoveBreakpointByID(break_id: m_break_id);
90 if (LLDB_BREAK_ID_IS_VALID(m_dyld_handover_break_id))
91 m_process->GetTarget().RemoveBreakpointByID(break_id: m_dyld_handover_break_id);
92}
93
94bool DynamicLoaderMacOS::ProcessDidExec() {
95 std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
96 bool did_exec = false;
97 if (m_process) {
98 // If we are stopped after an exec, we will have only one thread...
99 if (m_process->GetThreadList().GetSize() == 1) {
100 // Maybe we still have an image infos address around? If so see
101 // if that has changed, and if so we have exec'ed.
102 if (m_maybe_image_infos_address != LLDB_INVALID_ADDRESS) {
103 lldb::addr_t image_infos_address = m_process->GetImageInfoAddress();
104 if (image_infos_address != m_maybe_image_infos_address) {
105 // We don't really have to reset this here, since we are going to
106 // call DoInitialImageFetch right away to handle the exec. But in
107 // case anybody looks at it in the meantime, it can't hurt.
108 m_maybe_image_infos_address = image_infos_address;
109 did_exec = true;
110 }
111 }
112
113 if (!did_exec) {
114 // See if we are stopped at '_dyld_start'
115 ThreadSP thread_sp(m_process->GetThreadList().GetThreadAtIndex(idx: 0));
116 if (thread_sp) {
117 lldb::StackFrameSP frame_sp(thread_sp->GetStackFrameAtIndex(idx: 0));
118 if (frame_sp) {
119 const Symbol *symbol =
120 frame_sp->GetSymbolContext(resolve_scope: eSymbolContextSymbol).symbol;
121 if (symbol) {
122 if (symbol->GetName() == "_dyld_start")
123 did_exec = true;
124 }
125 }
126 }
127 }
128 }
129 }
130
131 if (did_exec) {
132 m_libpthread_module_wp.reset();
133 m_pthread_getspecific_addr.Clear();
134 m_libsystem_fully_initalized = false;
135 }
136 return did_exec;
137}
138
139// Clear out the state of this class.
140void DynamicLoaderMacOS::DoClear() {
141 std::lock_guard<std::recursive_mutex> guard(m_mutex);
142
143 if (LLDB_BREAK_ID_IS_VALID(m_break_id))
144 m_process->GetTarget().RemoveBreakpointByID(break_id: m_break_id);
145 if (LLDB_BREAK_ID_IS_VALID(m_dyld_handover_break_id))
146 m_process->GetTarget().RemoveBreakpointByID(break_id: m_dyld_handover_break_id);
147
148 m_break_id = LLDB_INVALID_BREAK_ID;
149 m_dyld_handover_break_id = LLDB_INVALID_BREAK_ID;
150 m_libsystem_fully_initalized = false;
151}
152
153bool DynamicLoaderMacOS::IsFullyInitialized() {
154 if (m_libsystem_fully_initalized)
155 return true;
156
157 StructuredData::ObjectSP process_state_sp(
158 m_process->GetDynamicLoaderProcessState());
159 if (!process_state_sp)
160 return true;
161 if (process_state_sp->GetAsDictionary()->HasKey(key: "error"))
162 return true;
163 if (!process_state_sp->GetAsDictionary()->HasKey(key: "process_state string"))
164 return true;
165 std::string proc_state = process_state_sp->GetAsDictionary()
166 ->GetValueForKey(key: "process_state string")
167 ->GetAsString()
168 ->GetValue()
169 .str();
170 if (proc_state == "dyld_process_state_not_started" ||
171 proc_state == "dyld_process_state_dyld_initialized" ||
172 proc_state == "dyld_process_state_terminated_before_inits") {
173 return false;
174 }
175 m_libsystem_fully_initalized = true;
176 return true;
177}
178
179// Check if we have found DYLD yet
180bool DynamicLoaderMacOS::DidSetNotificationBreakpoint() {
181 return LLDB_BREAK_ID_IS_VALID(m_break_id);
182}
183
184void DynamicLoaderMacOS::ClearNotificationBreakpoint() {
185 if (LLDB_BREAK_ID_IS_VALID(m_break_id)) {
186 m_process->GetTarget().RemoveBreakpointByID(break_id: m_break_id);
187 m_break_id = LLDB_INVALID_BREAK_ID;
188 }
189}
190
191// Try and figure out where dyld is by first asking the Process if it knows
192// (which currently calls down in the lldb::Process to get the DYLD info
193// (available on SnowLeopard only). If that fails, then check in the default
194// addresses.
195void DynamicLoaderMacOS::DoInitialImageFetch() {
196 Log *log = GetLog(mask: LLDBLog::DynamicLoader);
197
198 // Remove any binaries we pre-loaded in the Target before
199 // launching/attaching. If the same binaries are present in the process,
200 // we'll get them from the shared module cache, we won't need to re-load them
201 // from disk.
202 UnloadAllImages();
203
204 StructuredData::ObjectSP all_image_info_json_sp(
205 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(key: "images") &&
210 all_image_info_json_sp->GetAsDictionary()
211 ->GetValueForKey(key: "images")
212 ->GetAsArray()) {
213 if (JSONImageInformationIntoImageInfo(image_details: all_image_info_json_sp,
214 image_infos)) {
215 LLDB_LOGF(log, "Initial module fetch: Adding %" PRId64 " modules.\n",
216 (uint64_t)image_infos.size());
217
218 UpdateSpecialBinariesFromNewImageInfos(image_infos);
219 AddModulesUsingImageInfos(image_infos);
220 }
221 }
222
223 m_dyld_image_infos_stop_id = m_process->GetStopID();
224 m_maybe_image_infos_address = m_process->GetImageInfoAddress();
225}
226
227bool DynamicLoaderMacOS::NeedToDoInitialImageFetch() { return true; }
228
229// Static callback function that gets called when our DYLD notification
230// breakpoint gets hit. We update all of our image infos and then let our super
231// class DynamicLoader class decide if we should stop or not (based on global
232// preference).
233bool DynamicLoaderMacOS::NotifyBreakpointHit(void *baton,
234 StoppointCallbackContext *context,
235 lldb::user_id_t break_id,
236 lldb::user_id_t break_loc_id) {
237 //
238 // Our breakpoint on
239 //
240 // void lldb_image_notifier(enum dyld_image_mode mode, uint32_t infoCount,
241 // const dyld_image_info info[])
242 //
243 // has been hit. We need to read the arguments.
244
245 DynamicLoaderMacOS *dyld_instance = (DynamicLoaderMacOS *)baton;
246
247 ExecutionContext exe_ctx(context->exe_ctx_ref);
248 Process *process = exe_ctx.GetProcessPtr();
249
250 // This is a sanity check just in case this dyld_instance is an old dyld
251 // plugin's breakpoint still lying around.
252 if (process != dyld_instance->m_process)
253 return false;
254
255 if (dyld_instance->m_image_infos_stop_id != UINT32_MAX &&
256 process->GetStopID() < dyld_instance->m_image_infos_stop_id) {
257 return false;
258 }
259
260 const lldb::ABISP &abi = process->GetABI();
261 if (abi) {
262 // Build up the value array to store the three arguments given above, then
263 // get the values from the ABI:
264
265 TypeSystemClangSP scratch_ts_sp =
266 ScratchTypeSystemClang::GetForTarget(target&: process->GetTarget());
267 if (!scratch_ts_sp)
268 return false;
269
270 ValueList argument_values;
271
272 Value mode_value; // enum dyld_notify_mode { dyld_notify_adding=0,
273 // dyld_notify_removing=1, dyld_notify_remove_all=2,
274 // dyld_notify_dyld_moved=3 };
275 Value count_value; // uint32_t
276 Value headers_value; // struct dyld_image_info machHeaders[]
277
278 CompilerType clang_void_ptr_type =
279 scratch_ts_sp->GetBasicType(type: eBasicTypeVoid).GetPointerType();
280 CompilerType clang_uint32_type =
281 scratch_ts_sp->GetBuiltinTypeForEncodingAndBitSize(encoding: lldb::eEncodingUint,
282 bit_size: 32);
283 CompilerType clang_uint64_type =
284 scratch_ts_sp->GetBuiltinTypeForEncodingAndBitSize(encoding: lldb::eEncodingUint,
285 bit_size: 32);
286
287 mode_value.SetValueType(Value::ValueType::Scalar);
288 mode_value.SetCompilerType(clang_uint32_type);
289
290 count_value.SetValueType(Value::ValueType::Scalar);
291 count_value.SetCompilerType(clang_uint32_type);
292
293 headers_value.SetValueType(Value::ValueType::Scalar);
294 headers_value.SetCompilerType(clang_void_ptr_type);
295
296 argument_values.PushValue(value: mode_value);
297 argument_values.PushValue(value: count_value);
298 argument_values.PushValue(value: headers_value);
299
300 if (abi->GetArgumentValues(thread&: exe_ctx.GetThreadRef(), values&: argument_values)) {
301 uint32_t dyld_mode =
302 argument_values.GetValueAtIndex(idx: 0)->GetScalar().UInt(fail_value: -1);
303 if (dyld_mode != static_cast<uint32_t>(-1)) {
304 // Okay the mode was right, now get the number of elements, and the
305 // array of new elements...
306 uint32_t image_infos_count =
307 argument_values.GetValueAtIndex(idx: 1)->GetScalar().UInt(fail_value: -1);
308 if (image_infos_count != static_cast<uint32_t>(-1)) {
309 addr_t header_array =
310 argument_values.GetValueAtIndex(idx: 2)->GetScalar().ULongLong(fail_value: -1);
311 if (header_array != static_cast<uint64_t>(-1)) {
312 std::vector<addr_t> image_load_addresses;
313 // header_array points to an array of image_infos_count elements,
314 // each is
315 // struct dyld_image_info {
316 // const struct mach_header* imageLoadAddress;
317 // const char* imageFilePath;
318 // uintptr_t imageFileModDate;
319 // };
320 //
321 // and we only need the imageLoadAddress fields.
322
323 const int addrsize =
324 process->GetTarget().GetArchitecture().GetAddressByteSize();
325 for (uint64_t i = 0; i < image_infos_count; i++) {
326 Status error;
327 addr_t dyld_image_info = header_array + (addrsize * 3 * i);
328 addr_t addr =
329 process->ReadPointerFromMemory(vm_addr: dyld_image_info, error);
330 if (error.Success()) {
331 image_load_addresses.push_back(x: addr);
332 } else {
333 Debugger::ReportWarning(
334 message: "DynamicLoaderMacOS::NotifyBreakpointHit unable "
335 "to read binary mach-o load address at 0x%" PRIx64,
336 debugger_id: addr);
337 }
338 }
339 if (dyld_mode == 0) {
340 // dyld_notify_adding
341 if (process->GetTarget().GetImages().GetSize() == 0) {
342 // When all images have been removed, we're doing the
343 // dyld handover from a launch-dyld to a shared-cache-dyld,
344 // and we've just hit our one-shot address breakpoint in
345 // the sc-dyld. Note that the image addresses passed to
346 // this function are inferior sizeof(void*) not uint64_t's
347 // like our normal notification, so don't even look at
348 // image_load_addresses.
349
350 dyld_instance->ClearDYLDHandoverBreakpoint();
351
352 dyld_instance->DoInitialImageFetch();
353 dyld_instance->SetNotificationBreakpoint();
354 } else {
355 dyld_instance->AddBinaries(load_addresses: image_load_addresses);
356 }
357 } else if (dyld_mode == 1) {
358 // dyld_notify_removing
359 dyld_instance->UnloadImages(solib_addresses: image_load_addresses);
360 } else if (dyld_mode == 2) {
361 // dyld_notify_remove_all
362 dyld_instance->UnloadAllImages();
363 } else if (dyld_mode == 3 && image_infos_count == 1) {
364 // dyld_image_dyld_moved
365
366 dyld_instance->ClearNotificationBreakpoint();
367 dyld_instance->UnloadAllImages();
368 dyld_instance->ClearDYLDModule();
369 process->GetTarget().GetImages().Clear();
370 process->GetTarget().GetSectionLoadList().Clear();
371
372 addr_t all_image_infos = process->GetImageInfoAddress();
373 int addr_size =
374 process->GetTarget().GetArchitecture().GetAddressByteSize();
375 addr_t notification_location = all_image_infos + 4 + // version
376 4 + // infoArrayCount
377 addr_size; // infoArray
378 Status error;
379 addr_t notification_addr =
380 process->ReadPointerFromMemory(vm_addr: notification_location, error);
381 if (!error.Success()) {
382 Debugger::ReportWarning(
383 message: "DynamicLoaderMacOS::NotifyBreakpointHit unable "
384 "to read address of dyld-handover notification function at "
385 "0x%" PRIx64,
386 debugger_id: notification_location);
387 } else {
388 notification_addr = process->FixCodeAddress(pc: notification_addr);
389 dyld_instance->SetDYLDHandoverBreakpoint(notification_addr);
390 }
391 }
392 }
393 }
394 }
395 }
396 } else {
397 Target &target = process->GetTarget();
398 Debugger::ReportWarning(
399 message: "no ABI plugin located for triple " +
400 target.GetArchitecture().GetTriple().getTriple() +
401 ": shared libraries will not be registered",
402 debugger_id: target.GetDebugger().GetID());
403 }
404
405 // Return true to stop the target, false to just let the target run
406 return dyld_instance->GetStopWhenImagesChange();
407}
408
409void DynamicLoaderMacOS::AddBinaries(
410 const std::vector<lldb::addr_t> &load_addresses) {
411 Log *log = GetLog(mask: LLDBLog::DynamicLoader);
412 ImageInfo::collection image_infos;
413
414 LLDB_LOGF(log, "Adding %" PRId64 " modules.",
415 (uint64_t)load_addresses.size());
416 StructuredData::ObjectSP binaries_info_sp =
417 m_process->GetLoadedDynamicLibrariesInfos(load_addresses);
418 if (binaries_info_sp.get() && binaries_info_sp->GetAsDictionary() &&
419 binaries_info_sp->GetAsDictionary()->HasKey(key: "images") &&
420 binaries_info_sp->GetAsDictionary()
421 ->GetValueForKey(key: "images")
422 ->GetAsArray() &&
423 binaries_info_sp->GetAsDictionary()
424 ->GetValueForKey(key: "images")
425 ->GetAsArray()
426 ->GetSize() == load_addresses.size()) {
427 if (JSONImageInformationIntoImageInfo(image_details: binaries_info_sp, image_infos)) {
428 UpdateSpecialBinariesFromNewImageInfos(image_infos);
429 AddModulesUsingImageInfos(image_infos);
430 }
431 m_dyld_image_infos_stop_id = m_process->GetStopID();
432 }
433}
434
435// Dump the _dyld_all_image_infos members and all current image infos that we
436// have parsed to the file handle provided.
437void DynamicLoaderMacOS::PutToLog(Log *log) const {
438 if (log == nullptr)
439 return;
440}
441
442// Look in dyld's dyld_all_image_infos structure for the address
443// of the notification function.
444// We can find the address of dyld_all_image_infos by a system
445// call, even if we don't have a dyld binary registered in lldb's
446// image list.
447// At process launch time - before dyld has executed any instructions -
448// the address of the notification function is not a resolved vm address
449// yet. dyld_all_image_infos also has a field with its own address
450// in it, and this will also be unresolved when we're at this state.
451// So we can compare the address of the object with this field and if
452// they differ, dyld hasn't started executing yet and we can't get the
453// notification address this way.
454addr_t DynamicLoaderMacOS::GetNotificationFuncAddrFromImageInfos() {
455 addr_t notification_addr = LLDB_INVALID_ADDRESS;
456 if (!m_process)
457 return notification_addr;
458
459 addr_t all_image_infos_addr = m_process->GetImageInfoAddress();
460 if (all_image_infos_addr == LLDB_INVALID_ADDRESS)
461 return notification_addr;
462
463 const uint32_t addr_size =
464 m_process->GetTarget().GetArchitecture().GetAddressByteSize();
465 offset_t registered_infos_addr_offset =
466 sizeof(uint32_t) + // version
467 sizeof(uint32_t) + // infoArrayCount
468 addr_size + // infoArray
469 addr_size + // notification
470 addr_size + // processDetachedFromSharedRegion +
471 // libSystemInitialized + pad
472 addr_size + // dyldImageLoadAddress
473 addr_size + // jitInfo
474 addr_size + // dyldVersion
475 addr_size + // errorMessage
476 addr_size + // terminationFlags
477 addr_size + // coreSymbolicationShmPage
478 addr_size + // systemOrderFlag
479 addr_size + // uuidArrayCount
480 addr_size; // uuidArray
481 // dyldAllImageInfosAddress
482
483 // If the dyldAllImageInfosAddress does not match
484 // the actual address of this struct, dyld has not started
485 // executing yet. The 'notification' field can't be used by
486 // lldb until it's resolved to an actual address.
487 Status error;
488 addr_t registered_infos_addr = m_process->ReadPointerFromMemory(
489 vm_addr: all_image_infos_addr + registered_infos_addr_offset, error);
490 if (!error.Success())
491 return notification_addr;
492 if (registered_infos_addr != all_image_infos_addr)
493 return notification_addr;
494
495 offset_t notification_fptr_offset = sizeof(uint32_t) + // version
496 sizeof(uint32_t) + // infoArrayCount
497 addr_size; // infoArray
498
499 addr_t notification_fptr = m_process->ReadPointerFromMemory(
500 vm_addr: all_image_infos_addr + notification_fptr_offset, error);
501 if (error.Success())
502 notification_addr = m_process->FixCodeAddress(pc: notification_fptr);
503 return notification_addr;
504}
505
506// We want to put a breakpoint on dyld's lldb_image_notifier()
507// but we may have attached to the process during the
508// transition from on-disk-dyld to shared-cache-dyld, so there's
509// officially no dyld binary loaded in the process (libdyld will
510// report none when asked), but the kernel can find the dyld_all_image_infos
511// struct and the function pointer for lldb_image_notifier is in
512// that struct.
513bool DynamicLoaderMacOS::SetNotificationBreakpoint() {
514
515 // First try to find the notification breakpoint function by name
516 if (m_break_id == LLDB_INVALID_BREAK_ID) {
517 ModuleSP dyld_sp(GetDYLDModule());
518 if (dyld_sp) {
519 bool internal = true;
520 bool hardware = false;
521 LazyBool skip_prologue = eLazyBoolNo;
522 FileSpecList *source_files = nullptr;
523 FileSpecList dyld_filelist;
524 dyld_filelist.Append(file: dyld_sp->GetFileSpec());
525
526 Breakpoint *breakpoint =
527 m_process->GetTarget()
528 .CreateBreakpoint(containingModules: &dyld_filelist, containingSourceFiles: source_files,
529 func_name: "lldb_image_notifier", func_name_type_mask: eFunctionNameTypeFull,
530 language: eLanguageTypeUnknown, offset: 0, skip_prologue,
531 internal, request_hardware: hardware)
532 .get();
533 breakpoint->SetCallback(callback: DynamicLoaderMacOS::NotifyBreakpointHit, baton: this,
534 is_synchronous: true);
535 breakpoint->SetBreakpointKind("shared-library-event");
536 if (breakpoint->HasResolvedLocations())
537 m_break_id = breakpoint->GetID();
538 else
539 m_process->GetTarget().RemoveBreakpointByID(break_id: breakpoint->GetID());
540
541 if (m_break_id == LLDB_INVALID_BREAK_ID) {
542 Breakpoint *breakpoint =
543 m_process->GetTarget()
544 .CreateBreakpoint(containingModules: &dyld_filelist, containingSourceFiles: source_files,
545 func_name: "gdb_image_notifier", func_name_type_mask: eFunctionNameTypeFull,
546 language: eLanguageTypeUnknown, offset: 0, skip_prologue,
547 internal, request_hardware: hardware)
548 .get();
549 breakpoint->SetCallback(callback: DynamicLoaderMacOS::NotifyBreakpointHit, baton: this,
550 is_synchronous: true);
551 breakpoint->SetBreakpointKind("shared-library-event");
552 if (breakpoint->HasResolvedLocations())
553 m_break_id = breakpoint->GetID();
554 else
555 m_process->GetTarget().RemoveBreakpointByID(break_id: breakpoint->GetID());
556 }
557 }
558 }
559
560 // Failing that, find dyld_all_image_infos struct in memory,
561 // read the notification function pointer at the offset.
562 if (m_break_id == LLDB_INVALID_BREAK_ID) {
563 addr_t notification_addr = GetNotificationFuncAddrFromImageInfos();
564 if (notification_addr != LLDB_INVALID_ADDRESS) {
565 Address so_addr;
566 // We may not have a dyld binary mapped to this address yet;
567 // don't try to express the Address object as section+offset,
568 // only as a raw load address.
569 so_addr.SetRawAddress(notification_addr);
570 Breakpoint *dyld_break =
571 m_process->GetTarget().CreateBreakpoint(addr: so_addr, internal: true, request_hardware: false).get();
572 dyld_break->SetCallback(callback: DynamicLoaderMacOS::NotifyBreakpointHit, baton: this,
573 is_synchronous: true);
574 dyld_break->SetBreakpointKind("shared-library-event");
575 if (dyld_break->HasResolvedLocations())
576 m_break_id = dyld_break->GetID();
577 else
578 m_process->GetTarget().RemoveBreakpointByID(break_id: dyld_break->GetID());
579 }
580 }
581 return m_break_id != LLDB_INVALID_BREAK_ID;
582}
583
584bool DynamicLoaderMacOS::SetDYLDHandoverBreakpoint(
585 addr_t notification_address) {
586 if (m_dyld_handover_break_id == LLDB_INVALID_BREAK_ID) {
587 BreakpointSP dyld_handover_bp = m_process->GetTarget().CreateBreakpoint(
588 load_addr: notification_address, internal: true, request_hardware: false);
589 dyld_handover_bp->SetCallback(callback: DynamicLoaderMacOS::NotifyBreakpointHit, baton: this,
590 is_synchronous: true);
591 dyld_handover_bp->SetOneShot(true);
592 m_dyld_handover_break_id = dyld_handover_bp->GetID();
593 return true;
594 }
595 return false;
596}
597
598void DynamicLoaderMacOS::ClearDYLDHandoverBreakpoint() {
599 if (LLDB_BREAK_ID_IS_VALID(m_dyld_handover_break_id))
600 m_process->GetTarget().RemoveBreakpointByID(break_id: m_dyld_handover_break_id);
601 m_dyld_handover_break_id = LLDB_INVALID_BREAK_ID;
602}
603
604addr_t
605DynamicLoaderMacOS::GetDyldLockVariableAddressFromModule(Module *module) {
606 SymbolContext sc;
607 Target &target = m_process->GetTarget();
608 if (Symtab *symtab = module->GetSymtab()) {
609 std::vector<uint32_t> match_indexes;
610 ConstString g_symbol_name("_dyld_global_lock_held");
611 uint32_t num_matches = 0;
612 num_matches =
613 symtab->AppendSymbolIndexesWithName(symbol_name: g_symbol_name, matches&: match_indexes);
614 if (num_matches == 1) {
615 Symbol *symbol = symtab->SymbolAtIndex(idx: match_indexes[0]);
616 if (symbol &&
617 (symbol->ValueIsAddress() || symbol->GetAddressRef().IsValid())) {
618 return symbol->GetAddressRef().GetOpcodeLoadAddress(target: &target);
619 }
620 }
621 }
622 return LLDB_INVALID_ADDRESS;
623}
624
625// Look for this symbol:
626//
627// int __attribute__((visibility("hidden"))) _dyld_global_lock_held =
628// 0;
629//
630// in libdyld.dylib.
631Status DynamicLoaderMacOS::CanLoadImage() {
632 Status error;
633 addr_t symbol_address = LLDB_INVALID_ADDRESS;
634 ConstString g_libdyld_name("libdyld.dylib");
635 Target &target = m_process->GetTarget();
636 const ModuleList &target_modules = target.GetImages();
637 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
638
639 // Find any modules named "libdyld.dylib" and look for the symbol there first
640 for (ModuleSP module_sp : target.GetImages().ModulesNoLocking()) {
641 if (module_sp) {
642 if (module_sp->GetFileSpec().GetFilename() == g_libdyld_name) {
643 symbol_address = GetDyldLockVariableAddressFromModule(module: module_sp.get());
644 if (symbol_address != LLDB_INVALID_ADDRESS)
645 break;
646 }
647 }
648 }
649
650 // Search through all modules looking for the symbol in them
651 if (symbol_address == LLDB_INVALID_ADDRESS) {
652 for (ModuleSP module_sp : target.GetImages().Modules()) {
653 if (module_sp) {
654 addr_t symbol_address =
655 GetDyldLockVariableAddressFromModule(module: module_sp.get());
656 if (symbol_address != LLDB_INVALID_ADDRESS)
657 break;
658 }
659 }
660 }
661
662 // Default assumption is that it is OK to load images. Only say that we
663 // cannot load images if we find the symbol in libdyld and it indicates that
664 // we cannot.
665
666 if (symbol_address != LLDB_INVALID_ADDRESS) {
667 {
668 int lock_held =
669 m_process->ReadUnsignedIntegerFromMemory(load_addr: symbol_address, byte_size: 4, fail_value: 0, error);
670 if (lock_held != 0) {
671 error.SetErrorString("dyld lock held - unsafe to load images.");
672 }
673 }
674 } else {
675 // If we were unable to find _dyld_global_lock_held in any modules, or it
676 // is not loaded into memory yet, we may be at process startup (sitting at
677 // _dyld_start) - so we should not allow dlopen calls. But if we found more
678 // than one module then we are clearly past _dyld_start so in that case
679 // we'll default to "it's safe".
680 if (target.GetImages().GetSize() <= 1)
681 error.SetErrorString("could not find the dyld library or "
682 "the dyld lock symbol");
683 }
684 return error;
685}
686
687bool DynamicLoaderMacOS::GetSharedCacheInformation(
688 lldb::addr_t &base_address, UUID &uuid, LazyBool &using_shared_cache,
689 LazyBool &private_shared_cache) {
690 base_address = LLDB_INVALID_ADDRESS;
691 uuid.Clear();
692 using_shared_cache = eLazyBoolCalculate;
693 private_shared_cache = eLazyBoolCalculate;
694
695 if (m_process) {
696 StructuredData::ObjectSP info = m_process->GetSharedCacheInfo();
697 StructuredData::Dictionary *info_dict = nullptr;
698 if (info.get() && info->GetAsDictionary()) {
699 info_dict = info->GetAsDictionary();
700 }
701
702 // {"shared_cache_base_address":140735683125248,"shared_cache_uuid
703 // ":"DDB8D70C-
704 // C9A2-3561-B2C8-BE48A4F33F96","no_shared_cache":false,"shared_cache_private_cache":false}
705
706 if (info_dict && info_dict->HasKey(key: "shared_cache_uuid") &&
707 info_dict->HasKey(key: "no_shared_cache") &&
708 info_dict->HasKey(key: "shared_cache_base_address")) {
709 base_address = info_dict->GetValueForKey(key: "shared_cache_base_address")
710 ->GetUnsignedIntegerValue(LLDB_INVALID_ADDRESS);
711 std::string uuid_str = std::string(
712 info_dict->GetValueForKey(key: "shared_cache_uuid")->GetStringValue());
713 if (!uuid_str.empty())
714 uuid.SetFromStringRef(uuid_str);
715 if (!info_dict->GetValueForKey(key: "no_shared_cache")->GetBooleanValue())
716 using_shared_cache = eLazyBoolYes;
717 else
718 using_shared_cache = eLazyBoolNo;
719 if (info_dict->GetValueForKey(key: "shared_cache_private_cache")
720 ->GetBooleanValue())
721 private_shared_cache = eLazyBoolYes;
722 else
723 private_shared_cache = eLazyBoolNo;
724
725 return true;
726 }
727 }
728 return false;
729}
730
731void DynamicLoaderMacOS::Initialize() {
732 PluginManager::RegisterPlugin(name: GetPluginNameStatic(),
733 description: GetPluginDescriptionStatic(), create_callback: CreateInstance);
734}
735
736void DynamicLoaderMacOS::Terminate() {
737 PluginManager::UnregisterPlugin(create_callback: CreateInstance);
738}
739
740llvm::StringRef DynamicLoaderMacOS::GetPluginDescriptionStatic() {
741 return "Dynamic loader plug-in that watches for shared library loads/unloads "
742 "in MacOSX user processes.";
743}
744

source code of lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOS.cpp