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

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