1 //===-- DynamicLoaderMacOSXDYLD.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 "DynamicLoaderMacOSXDYLD.h"
10 #include "DynamicLoaderDarwin.h"
11 #include "DynamicLoaderMacOS.h"
12 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
13 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
14 #include "lldb/Breakpoint/StoppointCallbackContext.h"
15 #include "lldb/Core/Debugger.h"
16 #include "lldb/Core/Module.h"
17 #include "lldb/Core/ModuleSpec.h"
18 #include "lldb/Core/PluginManager.h"
19 #include "lldb/Core/Section.h"
20 #include "lldb/Symbol/Function.h"
21 #include "lldb/Symbol/ObjectFile.h"
22 #include "lldb/Target/ABI.h"
23 #include "lldb/Target/RegisterContext.h"
24 #include "lldb/Target/StackFrame.h"
25 #include "lldb/Target/Target.h"
26 #include "lldb/Target/Thread.h"
27 #include "lldb/Target/ThreadPlanRunToAddress.h"
28 #include "lldb/Utility/DataBuffer.h"
29 #include "lldb/Utility/DataBufferHeap.h"
30 #include "lldb/Utility/LLDBLog.h"
31 #include "lldb/Utility/Log.h"
32 #include "lldb/Utility/State.h"
33
34 //#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN
35 #ifdef ENABLE_DEBUG_PRINTF
36 #include <cstdio>
37 #define DEBUG_PRINTF(fmt, ...) printf(fmt, ##__VA_ARGS__)
38 #else
39 #define DEBUG_PRINTF(fmt, ...)
40 #endif
41
42 #ifndef __APPLE__
43 #include "Utility/UuidCompatibility.h"
44 #else
45 #include <uuid/uuid.h>
46 #endif
47
48 using namespace lldb;
49 using namespace lldb_private;
50
LLDB_PLUGIN_DEFINE(DynamicLoaderMacOSXDYLD)51 LLDB_PLUGIN_DEFINE(DynamicLoaderMacOSXDYLD)
52
53 // Create an instance of this class. This function is filled into the plugin
54 // info class that gets handed out by the plugin factory and allows the lldb to
55 // instantiate an instance of this class.
56 DynamicLoader *DynamicLoaderMacOSXDYLD::CreateInstance(Process *process,
57 bool force) {
58 bool create = force;
59 if (!create) {
60 create = true;
61 Module *exe_module = process->GetTarget().GetExecutableModulePointer();
62 if (exe_module) {
63 ObjectFile *object_file = exe_module->GetObjectFile();
64 if (object_file) {
65 create = (object_file->GetStrata() == ObjectFile::eStrataUser);
66 }
67 }
68
69 if (create) {
70 const llvm::Triple &triple_ref =
71 process->GetTarget().GetArchitecture().GetTriple();
72 switch (triple_ref.getOS()) {
73 case llvm::Triple::Darwin:
74 case llvm::Triple::MacOSX:
75 case llvm::Triple::IOS:
76 case llvm::Triple::TvOS:
77 case llvm::Triple::WatchOS:
78 // NEED_BRIDGEOS_TRIPLE case llvm::Triple::BridgeOS:
79 create = triple_ref.getVendor() == llvm::Triple::Apple;
80 break;
81 default:
82 create = false;
83 break;
84 }
85 }
86 }
87
88 if (UseDYLDSPI(process)) {
89 create = false;
90 }
91
92 if (create)
93 return new DynamicLoaderMacOSXDYLD(process);
94 return nullptr;
95 }
96
97 // Constructor
DynamicLoaderMacOSXDYLD(Process * process)98 DynamicLoaderMacOSXDYLD::DynamicLoaderMacOSXDYLD(Process *process)
99 : DynamicLoaderDarwin(process),
100 m_dyld_all_image_infos_addr(LLDB_INVALID_ADDRESS),
101 m_dyld_all_image_infos(), m_dyld_all_image_infos_stop_id(UINT32_MAX),
102 m_break_id(LLDB_INVALID_BREAK_ID), m_mutex(),
103 m_process_image_addr_is_all_images_infos(false) {}
104
105 // Destructor
~DynamicLoaderMacOSXDYLD()106 DynamicLoaderMacOSXDYLD::~DynamicLoaderMacOSXDYLD() {
107 if (LLDB_BREAK_ID_IS_VALID(m_break_id))
108 m_process->GetTarget().RemoveBreakpointByID(m_break_id);
109 }
110
ProcessDidExec()111 bool DynamicLoaderMacOSXDYLD::ProcessDidExec() {
112 std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
113 bool did_exec = false;
114 if (m_process) {
115 // If we are stopped after an exec, we will have only one thread...
116 if (m_process->GetThreadList().GetSize() == 1) {
117 // We know if a process has exec'ed if our "m_dyld_all_image_infos_addr"
118 // value differs from the Process' image info address. When a process
119 // execs itself it might cause a change if ASLR is enabled.
120 const addr_t shlib_addr = m_process->GetImageInfoAddress();
121 if (m_process_image_addr_is_all_images_infos &&
122 shlib_addr != m_dyld_all_image_infos_addr) {
123 // The image info address from the process is the
124 // 'dyld_all_image_infos' address and it has changed.
125 did_exec = true;
126 } else if (!m_process_image_addr_is_all_images_infos &&
127 shlib_addr == m_dyld.address) {
128 // The image info address from the process is the mach_header address
129 // for dyld and it has changed.
130 did_exec = true;
131 } else {
132 // ASLR might be disabled and dyld could have ended up in the same
133 // location. We should try and detect if we are stopped at
134 // '_dyld_start'
135 ThreadSP thread_sp(m_process->GetThreadList().GetThreadAtIndex(0));
136 if (thread_sp) {
137 lldb::StackFrameSP frame_sp(thread_sp->GetStackFrameAtIndex(0));
138 if (frame_sp) {
139 const Symbol *symbol =
140 frame_sp->GetSymbolContext(eSymbolContextSymbol).symbol;
141 if (symbol) {
142 if (symbol->GetName() == "_dyld_start")
143 did_exec = true;
144 }
145 }
146 }
147 }
148
149 if (did_exec) {
150 m_libpthread_module_wp.reset();
151 m_pthread_getspecific_addr.Clear();
152 }
153 }
154 }
155 return did_exec;
156 }
157
158 // Clear out the state of this class.
DoClear()159 void DynamicLoaderMacOSXDYLD::DoClear() {
160 std::lock_guard<std::recursive_mutex> guard(m_mutex);
161
162 if (LLDB_BREAK_ID_IS_VALID(m_break_id))
163 m_process->GetTarget().RemoveBreakpointByID(m_break_id);
164
165 m_dyld_all_image_infos_addr = LLDB_INVALID_ADDRESS;
166 m_dyld_all_image_infos.Clear();
167 m_break_id = LLDB_INVALID_BREAK_ID;
168 }
169
170 // Check if we have found DYLD yet
DidSetNotificationBreakpoint()171 bool DynamicLoaderMacOSXDYLD::DidSetNotificationBreakpoint() {
172 return LLDB_BREAK_ID_IS_VALID(m_break_id);
173 }
174
ClearNotificationBreakpoint()175 void DynamicLoaderMacOSXDYLD::ClearNotificationBreakpoint() {
176 if (LLDB_BREAK_ID_IS_VALID(m_break_id)) {
177 m_process->GetTarget().RemoveBreakpointByID(m_break_id);
178 }
179 }
180
181 // Try and figure out where dyld is by first asking the Process if it knows
182 // (which currently calls down in the lldb::Process to get the DYLD info
183 // (available on SnowLeopard only). If that fails, then check in the default
184 // addresses.
DoInitialImageFetch()185 void DynamicLoaderMacOSXDYLD::DoInitialImageFetch() {
186 if (m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS) {
187 // Check the image info addr as it might point to the mach header for dyld,
188 // or it might point to the dyld_all_image_infos struct
189 const addr_t shlib_addr = m_process->GetImageInfoAddress();
190 if (shlib_addr != LLDB_INVALID_ADDRESS) {
191 ByteOrder byte_order =
192 m_process->GetTarget().GetArchitecture().GetByteOrder();
193 uint8_t buf[4];
194 DataExtractor data(buf, sizeof(buf), byte_order, 4);
195 Status error;
196 if (m_process->ReadMemory(shlib_addr, buf, 4, error) == 4) {
197 lldb::offset_t offset = 0;
198 uint32_t magic = data.GetU32(&offset);
199 switch (magic) {
200 case llvm::MachO::MH_MAGIC:
201 case llvm::MachO::MH_MAGIC_64:
202 case llvm::MachO::MH_CIGAM:
203 case llvm::MachO::MH_CIGAM_64:
204 m_process_image_addr_is_all_images_infos = false;
205 ReadDYLDInfoFromMemoryAndSetNotificationCallback(shlib_addr);
206 return;
207
208 default:
209 break;
210 }
211 }
212 // Maybe it points to the all image infos?
213 m_dyld_all_image_infos_addr = shlib_addr;
214 m_process_image_addr_is_all_images_infos = true;
215 }
216 }
217
218 if (m_dyld_all_image_infos_addr != LLDB_INVALID_ADDRESS) {
219 if (ReadAllImageInfosStructure()) {
220 if (m_dyld_all_image_infos.dyldImageLoadAddress != LLDB_INVALID_ADDRESS)
221 ReadDYLDInfoFromMemoryAndSetNotificationCallback(
222 m_dyld_all_image_infos.dyldImageLoadAddress);
223 else
224 ReadDYLDInfoFromMemoryAndSetNotificationCallback(
225 m_dyld_all_image_infos_addr & 0xfffffffffff00000ull);
226 return;
227 }
228 }
229
230 // Check some default values
231 Module *executable = m_process->GetTarget().GetExecutableModulePointer();
232
233 if (executable) {
234 const ArchSpec &exe_arch = executable->GetArchitecture();
235 if (exe_arch.GetAddressByteSize() == 8) {
236 ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x7fff5fc00000ull);
237 } else if (exe_arch.GetMachine() == llvm::Triple::arm ||
238 exe_arch.GetMachine() == llvm::Triple::thumb ||
239 exe_arch.GetMachine() == llvm::Triple::aarch64 ||
240 exe_arch.GetMachine() == llvm::Triple::aarch64_32) {
241 ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x2fe00000);
242 } else {
243 ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x8fe00000);
244 }
245 }
246 }
247
248 // Assume that dyld is in memory at ADDR and try to parse it's load commands
ReadDYLDInfoFromMemoryAndSetNotificationCallback(lldb::addr_t addr)249 bool DynamicLoaderMacOSXDYLD::ReadDYLDInfoFromMemoryAndSetNotificationCallback(
250 lldb::addr_t addr) {
251 std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
252 DataExtractor data; // Load command data
253 static ConstString g_dyld_all_image_infos("dyld_all_image_infos");
254 static ConstString g_new_dyld_all_image_infos("dyld4::dyld_all_image_infos");
255 if (ReadMachHeader(addr, &m_dyld.header, &data)) {
256 if (m_dyld.header.filetype == llvm::MachO::MH_DYLINKER) {
257 m_dyld.address = addr;
258 ModuleSP dyld_module_sp;
259 if (ParseLoadCommands(data, m_dyld, &m_dyld.file_spec)) {
260 if (m_dyld.file_spec) {
261 UpdateDYLDImageInfoFromNewImageInfo(m_dyld);
262 }
263 }
264 dyld_module_sp = GetDYLDModule();
265
266 Target &target = m_process->GetTarget();
267
268 if (m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS &&
269 dyld_module_sp.get()) {
270 const Symbol *symbol = dyld_module_sp->FindFirstSymbolWithNameAndType(
271 g_dyld_all_image_infos, eSymbolTypeData);
272 if (!symbol) {
273 symbol = dyld_module_sp->FindFirstSymbolWithNameAndType(
274 g_new_dyld_all_image_infos, eSymbolTypeData);
275 }
276 if (symbol)
277 m_dyld_all_image_infos_addr = symbol->GetLoadAddress(&target);
278 }
279
280 if (m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS) {
281 ConstString g_sect_name("__all_image_info");
282 SectionSP dyld_aii_section_sp =
283 dyld_module_sp->GetSectionList()->FindSectionByName(g_sect_name);
284 if (dyld_aii_section_sp) {
285 Address dyld_aii_addr(dyld_aii_section_sp, 0);
286 m_dyld_all_image_infos_addr = dyld_aii_addr.GetLoadAddress(&target);
287 }
288 }
289
290 // Update all image infos
291 InitializeFromAllImageInfos();
292
293 // If we didn't have an executable before, but now we do, then the dyld
294 // module shared pointer might be unique and we may need to add it again
295 // (since Target::SetExecutableModule() will clear the images). So append
296 // the dyld module back to the list if it is
297 /// unique!
298 if (dyld_module_sp) {
299 target.GetImages().AppendIfNeeded(dyld_module_sp);
300
301 // At this point we should have read in dyld's module, and so we should
302 // set breakpoints in it:
303 ModuleList modules;
304 modules.Append(dyld_module_sp);
305 target.ModulesDidLoad(modules);
306 SetDYLDModule(dyld_module_sp);
307 }
308
309 return true;
310 }
311 }
312 return false;
313 }
314
NeedToDoInitialImageFetch()315 bool DynamicLoaderMacOSXDYLD::NeedToDoInitialImageFetch() {
316 return m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS;
317 }
318
319 // Static callback function that gets called when our DYLD notification
320 // breakpoint gets hit. We update all of our image infos and then let our super
321 // class DynamicLoader class decide if we should stop or not (based on global
322 // preference).
NotifyBreakpointHit(void * baton,StoppointCallbackContext * context,lldb::user_id_t break_id,lldb::user_id_t break_loc_id)323 bool DynamicLoaderMacOSXDYLD::NotifyBreakpointHit(
324 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
325 lldb::user_id_t break_loc_id) {
326 // Let the event know that the images have changed
327 // DYLD passes three arguments to the notification breakpoint.
328 // Arg1: enum dyld_image_mode mode - 0 = adding, 1 = removing Arg2: uint32_t
329 // infoCount - Number of shared libraries added Arg3: dyld_image_info
330 // info[] - Array of structs of the form:
331 // const struct mach_header
332 // *imageLoadAddress
333 // const char *imageFilePath
334 // uintptr_t imageFileModDate (a time_t)
335
336 DynamicLoaderMacOSXDYLD *dyld_instance = (DynamicLoaderMacOSXDYLD *)baton;
337
338 // First step is to see if we've already initialized the all image infos. If
339 // we haven't then this function will do so and return true. In the course
340 // of initializing the all_image_infos it will read the complete current
341 // state, so we don't need to figure out what has changed from the data
342 // passed in to us.
343
344 ExecutionContext exe_ctx(context->exe_ctx_ref);
345 Process *process = exe_ctx.GetProcessPtr();
346
347 // This is a sanity check just in case this dyld_instance is an old dyld
348 // plugin's breakpoint still lying around.
349 if (process != dyld_instance->m_process)
350 return false;
351
352 if (dyld_instance->InitializeFromAllImageInfos())
353 return dyld_instance->GetStopWhenImagesChange();
354
355 const lldb::ABISP &abi = process->GetABI();
356 if (abi) {
357 // Build up the value array to store the three arguments given above, then
358 // get the values from the ABI:
359
360 TypeSystemClangSP scratch_ts_sp =
361 ScratchTypeSystemClang::GetForTarget(process->GetTarget());
362 if (!scratch_ts_sp)
363 return false;
364
365 ValueList argument_values;
366 Value input_value;
367
368 CompilerType clang_void_ptr_type =
369 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
370 CompilerType clang_uint32_type =
371 scratch_ts_sp->GetBuiltinTypeForEncodingAndBitSize(lldb::eEncodingUint,
372 32);
373 input_value.SetValueType(Value::ValueType::Scalar);
374 input_value.SetCompilerType(clang_uint32_type);
375 // input_value.SetContext (Value::eContextTypeClangType,
376 // clang_uint32_type);
377 argument_values.PushValue(input_value);
378 argument_values.PushValue(input_value);
379 input_value.SetCompilerType(clang_void_ptr_type);
380 // input_value.SetContext (Value::eContextTypeClangType,
381 // clang_void_ptr_type);
382 argument_values.PushValue(input_value);
383
384 if (abi->GetArgumentValues(exe_ctx.GetThreadRef(), argument_values)) {
385 uint32_t dyld_mode =
386 argument_values.GetValueAtIndex(0)->GetScalar().UInt(-1);
387 if (dyld_mode != static_cast<uint32_t>(-1)) {
388 // Okay the mode was right, now get the number of elements, and the
389 // array of new elements...
390 uint32_t image_infos_count =
391 argument_values.GetValueAtIndex(1)->GetScalar().UInt(-1);
392 if (image_infos_count != static_cast<uint32_t>(-1)) {
393 // Got the number added, now go through the array of added elements,
394 // putting out the mach header address, and adding the image. Note,
395 // I'm not putting in logging here, since the AddModules &
396 // RemoveModules functions do all the logging internally.
397
398 lldb::addr_t image_infos_addr =
399 argument_values.GetValueAtIndex(2)->GetScalar().ULongLong();
400 if (dyld_mode == 0) {
401 // This is add:
402 dyld_instance->AddModulesUsingImageInfosAddress(image_infos_addr,
403 image_infos_count);
404 } else {
405 // This is remove:
406 dyld_instance->RemoveModulesUsingImageInfosAddress(
407 image_infos_addr, image_infos_count);
408 }
409 }
410 }
411 }
412 } else {
413 Target &target = process->GetTarget();
414 Debugger::ReportWarning(
415 "no ABI plugin located for triple " +
416 target.GetArchitecture().GetTriple().getTriple() +
417 ": shared libraries will not be registered",
418 target.GetDebugger().GetID());
419 }
420
421 // Return true to stop the target, false to just let the target run
422 return dyld_instance->GetStopWhenImagesChange();
423 }
424
ReadAllImageInfosStructure()425 bool DynamicLoaderMacOSXDYLD::ReadAllImageInfosStructure() {
426 std::lock_guard<std::recursive_mutex> guard(m_mutex);
427
428 // the all image infos is already valid for this process stop ID
429 if (m_process->GetStopID() == m_dyld_all_image_infos_stop_id)
430 return true;
431
432 m_dyld_all_image_infos.Clear();
433 if (m_dyld_all_image_infos_addr != LLDB_INVALID_ADDRESS) {
434 ByteOrder byte_order =
435 m_process->GetTarget().GetArchitecture().GetByteOrder();
436 uint32_t addr_size =
437 m_process->GetTarget().GetArchitecture().GetAddressByteSize();
438
439 uint8_t buf[256];
440 DataExtractor data(buf, sizeof(buf), byte_order, addr_size);
441 lldb::offset_t offset = 0;
442
443 const size_t count_v2 = sizeof(uint32_t) + // version
444 sizeof(uint32_t) + // infoArrayCount
445 addr_size + // infoArray
446 addr_size + // notification
447 addr_size + // processDetachedFromSharedRegion +
448 // libSystemInitialized + pad
449 addr_size; // dyldImageLoadAddress
450 const size_t count_v11 = count_v2 + addr_size + // jitInfo
451 addr_size + // dyldVersion
452 addr_size + // errorMessage
453 addr_size + // terminationFlags
454 addr_size + // coreSymbolicationShmPage
455 addr_size + // systemOrderFlag
456 addr_size + // uuidArrayCount
457 addr_size + // uuidArray
458 addr_size + // dyldAllImageInfosAddress
459 addr_size + // initialImageCount
460 addr_size + // errorKind
461 addr_size + // errorClientOfDylibPath
462 addr_size + // errorTargetDylibPath
463 addr_size; // errorSymbol
464 const size_t count_v13 = count_v11 + addr_size + // sharedCacheSlide
465 sizeof(uuid_t); // sharedCacheUUID
466 UNUSED_IF_ASSERT_DISABLED(count_v13);
467 assert(sizeof(buf) >= count_v13);
468
469 Status error;
470 if (m_process->ReadMemory(m_dyld_all_image_infos_addr, buf, 4, error) ==
471 4) {
472 m_dyld_all_image_infos.version = data.GetU32(&offset);
473 // If anything in the high byte is set, we probably got the byte order
474 // incorrect (the process might not have it set correctly yet due to
475 // attaching to a program without a specified file).
476 if (m_dyld_all_image_infos.version & 0xff000000) {
477 // We have guessed the wrong byte order. Swap it and try reading the
478 // version again.
479 if (byte_order == eByteOrderLittle)
480 byte_order = eByteOrderBig;
481 else
482 byte_order = eByteOrderLittle;
483
484 data.SetByteOrder(byte_order);
485 offset = 0;
486 m_dyld_all_image_infos.version = data.GetU32(&offset);
487 }
488 } else {
489 return false;
490 }
491
492 const size_t count =
493 (m_dyld_all_image_infos.version >= 11) ? count_v11 : count_v2;
494
495 const size_t bytes_read =
496 m_process->ReadMemory(m_dyld_all_image_infos_addr, buf, count, error);
497 if (bytes_read == count) {
498 offset = 0;
499 m_dyld_all_image_infos.version = data.GetU32(&offset);
500 m_dyld_all_image_infos.dylib_info_count = data.GetU32(&offset);
501 m_dyld_all_image_infos.dylib_info_addr = data.GetAddress(&offset);
502 m_dyld_all_image_infos.notification = data.GetAddress(&offset);
503 m_dyld_all_image_infos.processDetachedFromSharedRegion =
504 data.GetU8(&offset);
505 m_dyld_all_image_infos.libSystemInitialized = data.GetU8(&offset);
506 // Adjust for padding.
507 offset += addr_size - 2;
508 m_dyld_all_image_infos.dyldImageLoadAddress = data.GetAddress(&offset);
509 if (m_dyld_all_image_infos.version >= 11) {
510 offset += addr_size * 8;
511 uint64_t dyld_all_image_infos_addr = data.GetAddress(&offset);
512
513 // When we started, we were given the actual address of the
514 // all_image_infos struct (probably via TASK_DYLD_INFO) in memory -
515 // this address is stored in m_dyld_all_image_infos_addr and is the
516 // most accurate address we have.
517
518 // We read the dyld_all_image_infos struct from memory; it contains its
519 // own address. If the address in the struct does not match the actual
520 // address, the dyld we're looking at has been loaded at a different
521 // location (slid) from where it intended to load. The addresses in
522 // the dyld_all_image_infos struct are the original, non-slid
523 // addresses, and need to be adjusted. Most importantly the address of
524 // dyld and the notification address need to be adjusted.
525
526 if (dyld_all_image_infos_addr != m_dyld_all_image_infos_addr) {
527 uint64_t image_infos_offset =
528 dyld_all_image_infos_addr -
529 m_dyld_all_image_infos.dyldImageLoadAddress;
530 uint64_t notification_offset =
531 m_dyld_all_image_infos.notification -
532 m_dyld_all_image_infos.dyldImageLoadAddress;
533 m_dyld_all_image_infos.dyldImageLoadAddress =
534 m_dyld_all_image_infos_addr - image_infos_offset;
535 m_dyld_all_image_infos.notification =
536 m_dyld_all_image_infos.dyldImageLoadAddress + notification_offset;
537 }
538 }
539 m_dyld_all_image_infos_stop_id = m_process->GetStopID();
540 return true;
541 }
542 }
543 return false;
544 }
545
AddModulesUsingImageInfosAddress(lldb::addr_t image_infos_addr,uint32_t image_infos_count)546 bool DynamicLoaderMacOSXDYLD::AddModulesUsingImageInfosAddress(
547 lldb::addr_t image_infos_addr, uint32_t image_infos_count) {
548 ImageInfo::collection image_infos;
549 Log *log = GetLog(LLDBLog::DynamicLoader);
550 LLDB_LOGF(log, "Adding %d modules.\n", image_infos_count);
551
552 std::lock_guard<std::recursive_mutex> guard(m_mutex);
553 std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
554 if (m_process->GetStopID() == m_dyld_image_infos_stop_id)
555 return true;
556
557 StructuredData::ObjectSP image_infos_json_sp =
558 m_process->GetLoadedDynamicLibrariesInfos(image_infos_addr,
559 image_infos_count);
560 if (image_infos_json_sp.get() && image_infos_json_sp->GetAsDictionary() &&
561 image_infos_json_sp->GetAsDictionary()->HasKey("images") &&
562 image_infos_json_sp->GetAsDictionary()
563 ->GetValueForKey("images")
564 ->GetAsArray() &&
565 image_infos_json_sp->GetAsDictionary()
566 ->GetValueForKey("images")
567 ->GetAsArray()
568 ->GetSize() == image_infos_count) {
569 bool return_value = false;
570 if (JSONImageInformationIntoImageInfo(image_infos_json_sp, image_infos)) {
571 UpdateSpecialBinariesFromNewImageInfos(image_infos);
572 return_value = AddModulesUsingImageInfos(image_infos);
573 }
574 m_dyld_image_infos_stop_id = m_process->GetStopID();
575 return return_value;
576 }
577
578 if (!ReadImageInfos(image_infos_addr, image_infos_count, image_infos))
579 return false;
580
581 UpdateImageInfosHeaderAndLoadCommands(image_infos, image_infos_count, false);
582 bool return_value = AddModulesUsingImageInfos(image_infos);
583 m_dyld_image_infos_stop_id = m_process->GetStopID();
584 return return_value;
585 }
586
RemoveModulesUsingImageInfosAddress(lldb::addr_t image_infos_addr,uint32_t image_infos_count)587 bool DynamicLoaderMacOSXDYLD::RemoveModulesUsingImageInfosAddress(
588 lldb::addr_t image_infos_addr, uint32_t image_infos_count) {
589 ImageInfo::collection image_infos;
590 Log *log = GetLog(LLDBLog::DynamicLoader);
591
592 std::lock_guard<std::recursive_mutex> guard(m_mutex);
593 std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
594 if (m_process->GetStopID() == m_dyld_image_infos_stop_id)
595 return true;
596
597 // First read in the image_infos for the removed modules, and their headers &
598 // load commands.
599 if (!ReadImageInfos(image_infos_addr, image_infos_count, image_infos)) {
600 if (log)
601 log->PutCString("Failed reading image infos array.");
602 return false;
603 }
604
605 LLDB_LOGF(log, "Removing %d modules.", image_infos_count);
606
607 ModuleList unloaded_module_list;
608 for (uint32_t idx = 0; idx < image_infos.size(); ++idx) {
609 if (log) {
610 LLDB_LOGF(log, "Removing module at address=0x%16.16" PRIx64 ".",
611 image_infos[idx].address);
612 image_infos[idx].PutToLog(log);
613 }
614
615 // Remove this image_infos from the m_all_image_infos. We do the
616 // comparison by address rather than by file spec because we can have many
617 // modules with the same "file spec" in the case that they are modules
618 // loaded from memory.
619 //
620 // Also copy over the uuid from the old entry to the removed entry so we
621 // can use it to lookup the module in the module list.
622
623 bool found = false;
624
625 for (ImageInfo::collection::iterator pos = m_dyld_image_infos.begin();
626 pos != m_dyld_image_infos.end(); pos++) {
627 if (image_infos[idx].address == (*pos).address) {
628 image_infos[idx].uuid = (*pos).uuid;
629
630 // Add the module from this image_info to the "unloaded_module_list".
631 // We'll remove them all at one go later on.
632
633 ModuleSP unload_image_module_sp(
634 FindTargetModuleForImageInfo(image_infos[idx], false, nullptr));
635 if (unload_image_module_sp.get()) {
636 // When we unload, be sure to use the image info from the old list,
637 // since that has sections correctly filled in.
638 UnloadModuleSections(unload_image_module_sp.get(), *pos);
639 unloaded_module_list.AppendIfNeeded(unload_image_module_sp);
640 } else {
641 if (log) {
642 LLDB_LOGF(log, "Could not find module for unloading info entry:");
643 image_infos[idx].PutToLog(log);
644 }
645 }
646
647 // Then remove it from the m_dyld_image_infos:
648
649 m_dyld_image_infos.erase(pos);
650 found = true;
651 break;
652 }
653 }
654
655 if (!found) {
656 if (log) {
657 LLDB_LOGF(log, "Could not find image_info entry for unloading image:");
658 image_infos[idx].PutToLog(log);
659 }
660 }
661 }
662 if (unloaded_module_list.GetSize() > 0) {
663 if (log) {
664 log->PutCString("Unloaded:");
665 unloaded_module_list.LogUUIDAndPaths(
666 log, "DynamicLoaderMacOSXDYLD::ModulesDidUnload");
667 }
668 m_process->GetTarget().GetImages().Remove(unloaded_module_list);
669 }
670 m_dyld_image_infos_stop_id = m_process->GetStopID();
671 return true;
672 }
673
ReadImageInfos(lldb::addr_t image_infos_addr,uint32_t image_infos_count,ImageInfo::collection & image_infos)674 bool DynamicLoaderMacOSXDYLD::ReadImageInfos(
675 lldb::addr_t image_infos_addr, uint32_t image_infos_count,
676 ImageInfo::collection &image_infos) {
677 std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
678 const ByteOrder endian = GetByteOrderFromMagic(m_dyld.header.magic);
679 const uint32_t addr_size = m_dyld.GetAddressByteSize();
680
681 image_infos.resize(image_infos_count);
682 const size_t count = image_infos.size() * 3 * addr_size;
683 DataBufferHeap info_data(count, 0);
684 Status error;
685 const size_t bytes_read = m_process->ReadMemory(
686 image_infos_addr, info_data.GetBytes(), info_data.GetByteSize(), error);
687 if (bytes_read == count) {
688 lldb::offset_t info_data_offset = 0;
689 DataExtractor info_data_ref(info_data.GetBytes(), info_data.GetByteSize(),
690 endian, addr_size);
691 for (size_t i = 0;
692 i < image_infos.size() && info_data_ref.ValidOffset(info_data_offset);
693 i++) {
694 image_infos[i].address = info_data_ref.GetAddress(&info_data_offset);
695 lldb::addr_t path_addr = info_data_ref.GetAddress(&info_data_offset);
696 image_infos[i].mod_date = info_data_ref.GetAddress(&info_data_offset);
697
698 char raw_path[PATH_MAX];
699 m_process->ReadCStringFromMemory(path_addr, raw_path, sizeof(raw_path),
700 error);
701 // don't resolve the path
702 if (error.Success()) {
703 image_infos[i].file_spec.SetFile(raw_path, FileSpec::Style::native);
704 }
705 }
706 return true;
707 } else {
708 return false;
709 }
710 }
711
712 // If we have found where the "_dyld_all_image_infos" lives in memory, read the
713 // current info from it, and then update all image load addresses (or lack
714 // thereof). Only do this if this is the first time we're reading the dyld
715 // infos. Return true if we actually read anything, and false otherwise.
InitializeFromAllImageInfos()716 bool DynamicLoaderMacOSXDYLD::InitializeFromAllImageInfos() {
717 Log *log = GetLog(LLDBLog::DynamicLoader);
718
719 std::lock_guard<std::recursive_mutex> guard(m_mutex);
720 std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
721 if (m_process->GetStopID() == m_dyld_image_infos_stop_id ||
722 m_dyld_image_infos.size() != 0)
723 return false;
724
725 if (ReadAllImageInfosStructure()) {
726 // Nothing to load or unload?
727 if (m_dyld_all_image_infos.dylib_info_count == 0)
728 return true;
729
730 if (m_dyld_all_image_infos.dylib_info_addr == 0) {
731 // DYLD is updating the images now. So we should say we have no images,
732 // and then we'll
733 // figure it out when we hit the added breakpoint.
734 return false;
735 } else {
736 if (!AddModulesUsingImageInfosAddress(
737 m_dyld_all_image_infos.dylib_info_addr,
738 m_dyld_all_image_infos.dylib_info_count)) {
739 DEBUG_PRINTF("%s", "unable to read all data for all_dylib_infos.");
740 m_dyld_image_infos.clear();
741 }
742 }
743
744 // Now we have one more bit of business. If there is a library left in the
745 // images for our target that doesn't have a load address, then it must be
746 // something that we were expecting to load (for instance we read a load
747 // command for it) but it didn't in fact load - probably because
748 // DYLD_*_PATH pointed to an equivalent version. We don't want it to stay
749 // in the target's module list or it will confuse us, so unload it here.
750 Target &target = m_process->GetTarget();
751 ModuleList not_loaded_modules;
752 for (ModuleSP module_sp : target.GetImages().Modules()) {
753 if (!module_sp->IsLoadedInTarget(&target)) {
754 if (log) {
755 StreamString s;
756 module_sp->GetDescription(s.AsRawOstream());
757 LLDB_LOGF(log, "Unloading pre-run module: %s.", s.GetData());
758 }
759 not_loaded_modules.Append(module_sp);
760 }
761 }
762
763 if (not_loaded_modules.GetSize() != 0) {
764 target.GetImages().Remove(not_loaded_modules);
765 }
766
767 return true;
768 } else
769 return false;
770 }
771
772 // Read a mach_header at ADDR into HEADER, and also fill in the load command
773 // data into LOAD_COMMAND_DATA if it is non-NULL.
774 //
775 // Returns true if we succeed, false if we fail for any reason.
ReadMachHeader(lldb::addr_t addr,llvm::MachO::mach_header * header,DataExtractor * load_command_data)776 bool DynamicLoaderMacOSXDYLD::ReadMachHeader(lldb::addr_t addr,
777 llvm::MachO::mach_header *header,
778 DataExtractor *load_command_data) {
779 DataBufferHeap header_bytes(sizeof(llvm::MachO::mach_header), 0);
780 Status error;
781 size_t bytes_read = m_process->ReadMemory(addr, header_bytes.GetBytes(),
782 header_bytes.GetByteSize(), error);
783 if (bytes_read == sizeof(llvm::MachO::mach_header)) {
784 lldb::offset_t offset = 0;
785 ::memset(header, 0, sizeof(llvm::MachO::mach_header));
786
787 // Get the magic byte unswapped so we can figure out what we are dealing
788 // with
789 DataExtractor data(header_bytes.GetBytes(), header_bytes.GetByteSize(),
790 endian::InlHostByteOrder(), 4);
791 header->magic = data.GetU32(&offset);
792 lldb::addr_t load_cmd_addr = addr;
793 data.SetByteOrder(
794 DynamicLoaderMacOSXDYLD::GetByteOrderFromMagic(header->magic));
795 switch (header->magic) {
796 case llvm::MachO::MH_MAGIC:
797 case llvm::MachO::MH_CIGAM:
798 data.SetAddressByteSize(4);
799 load_cmd_addr += sizeof(llvm::MachO::mach_header);
800 break;
801
802 case llvm::MachO::MH_MAGIC_64:
803 case llvm::MachO::MH_CIGAM_64:
804 data.SetAddressByteSize(8);
805 load_cmd_addr += sizeof(llvm::MachO::mach_header_64);
806 break;
807
808 default:
809 return false;
810 }
811
812 // Read the rest of dyld's mach header
813 if (data.GetU32(&offset, &header->cputype,
814 (sizeof(llvm::MachO::mach_header) / sizeof(uint32_t)) -
815 1)) {
816 if (load_command_data == nullptr)
817 return true; // We were able to read the mach_header and weren't asked
818 // to read the load command bytes
819
820 WritableDataBufferSP load_cmd_data_sp(
821 new DataBufferHeap(header->sizeofcmds, 0));
822
823 size_t load_cmd_bytes_read =
824 m_process->ReadMemory(load_cmd_addr, load_cmd_data_sp->GetBytes(),
825 load_cmd_data_sp->GetByteSize(), error);
826
827 if (load_cmd_bytes_read == header->sizeofcmds) {
828 // Set the load command data and also set the correct endian swap
829 // settings and the correct address size
830 load_command_data->SetData(load_cmd_data_sp, 0, header->sizeofcmds);
831 load_command_data->SetByteOrder(data.GetByteOrder());
832 load_command_data->SetAddressByteSize(data.GetAddressByteSize());
833 return true; // We successfully read the mach_header and the load
834 // command data
835 }
836
837 return false; // We weren't able to read the load command data
838 }
839 }
840 return false; // We failed the read the mach_header
841 }
842
843 // Parse the load commands for an image
ParseLoadCommands(const DataExtractor & data,ImageInfo & dylib_info,FileSpec * lc_id_dylinker)844 uint32_t DynamicLoaderMacOSXDYLD::ParseLoadCommands(const DataExtractor &data,
845 ImageInfo &dylib_info,
846 FileSpec *lc_id_dylinker) {
847 lldb::offset_t offset = 0;
848 uint32_t cmd_idx;
849 Segment segment;
850 dylib_info.Clear(true);
851
852 for (cmd_idx = 0; cmd_idx < dylib_info.header.ncmds; cmd_idx++) {
853 // Clear out any load command specific data from DYLIB_INFO since we are
854 // about to read it.
855
856 if (data.ValidOffsetForDataOfSize(offset,
857 sizeof(llvm::MachO::load_command))) {
858 llvm::MachO::load_command load_cmd;
859 lldb::offset_t load_cmd_offset = offset;
860 load_cmd.cmd = data.GetU32(&offset);
861 load_cmd.cmdsize = data.GetU32(&offset);
862 switch (load_cmd.cmd) {
863 case llvm::MachO::LC_SEGMENT: {
864 segment.name.SetTrimmedCStringWithLength(
865 (const char *)data.GetData(&offset, 16), 16);
866 // We are putting 4 uint32_t values 4 uint64_t values so we have to use
867 // multiple 32 bit gets below.
868 segment.vmaddr = data.GetU32(&offset);
869 segment.vmsize = data.GetU32(&offset);
870 segment.fileoff = data.GetU32(&offset);
871 segment.filesize = data.GetU32(&offset);
872 // Extract maxprot, initprot, nsects and flags all at once
873 data.GetU32(&offset, &segment.maxprot, 4);
874 dylib_info.segments.push_back(segment);
875 } break;
876
877 case llvm::MachO::LC_SEGMENT_64: {
878 segment.name.SetTrimmedCStringWithLength(
879 (const char *)data.GetData(&offset, 16), 16);
880 // Extract vmaddr, vmsize, fileoff, and filesize all at once
881 data.GetU64(&offset, &segment.vmaddr, 4);
882 // Extract maxprot, initprot, nsects and flags all at once
883 data.GetU32(&offset, &segment.maxprot, 4);
884 dylib_info.segments.push_back(segment);
885 } break;
886
887 case llvm::MachO::LC_ID_DYLINKER:
888 if (lc_id_dylinker) {
889 const lldb::offset_t name_offset =
890 load_cmd_offset + data.GetU32(&offset);
891 const char *path = data.PeekCStr(name_offset);
892 lc_id_dylinker->SetFile(path, FileSpec::Style::native);
893 FileSystem::Instance().Resolve(*lc_id_dylinker);
894 }
895 break;
896
897 case llvm::MachO::LC_UUID:
898 dylib_info.uuid = UUID(data.GetData(&offset, 16), 16);
899 break;
900
901 default:
902 break;
903 }
904 // Set offset to be the beginning of the next load command.
905 offset = load_cmd_offset + load_cmd.cmdsize;
906 }
907 }
908
909 // All sections listed in the dyld image info structure will all either be
910 // fixed up already, or they will all be off by a single slide amount that is
911 // determined by finding the first segment that is at file offset zero which
912 // also has bytes (a file size that is greater than zero) in the object file.
913
914 // Determine the slide amount (if any)
915 const size_t num_sections = dylib_info.segments.size();
916 for (size_t i = 0; i < num_sections; ++i) {
917 // Iterate through the object file sections to find the first section that
918 // starts of file offset zero and that has bytes in the file...
919 if ((dylib_info.segments[i].fileoff == 0 &&
920 dylib_info.segments[i].filesize > 0) ||
921 (dylib_info.segments[i].name == "__TEXT")) {
922 dylib_info.slide = dylib_info.address - dylib_info.segments[i].vmaddr;
923 // We have found the slide amount, so we can exit this for loop.
924 break;
925 }
926 }
927 return cmd_idx;
928 }
929
930 // Read the mach_header and load commands for each image that the
931 // _dyld_all_image_infos structure points to and cache the results.
932
UpdateImageInfosHeaderAndLoadCommands(ImageInfo::collection & image_infos,uint32_t infos_count,bool update_executable)933 void DynamicLoaderMacOSXDYLD::UpdateImageInfosHeaderAndLoadCommands(
934 ImageInfo::collection &image_infos, uint32_t infos_count,
935 bool update_executable) {
936 uint32_t exe_idx = UINT32_MAX;
937 // Read any UUID values that we can get
938 for (uint32_t i = 0; i < infos_count; i++) {
939 if (!image_infos[i].UUIDValid()) {
940 DataExtractor data; // Load command data
941 if (!ReadMachHeader(image_infos[i].address, &image_infos[i].header,
942 &data))
943 continue;
944
945 ParseLoadCommands(data, image_infos[i], nullptr);
946
947 if (image_infos[i].header.filetype == llvm::MachO::MH_EXECUTE)
948 exe_idx = i;
949 }
950 }
951
952 Target &target = m_process->GetTarget();
953
954 if (exe_idx < image_infos.size()) {
955 const bool can_create = true;
956 ModuleSP exe_module_sp(FindTargetModuleForImageInfo(image_infos[exe_idx],
957 can_create, nullptr));
958
959 if (exe_module_sp) {
960 UpdateImageLoadAddress(exe_module_sp.get(), image_infos[exe_idx]);
961
962 if (exe_module_sp.get() != target.GetExecutableModulePointer()) {
963 // Don't load dependent images since we are in dyld where we will know
964 // and find out about all images that are loaded. Also when setting the
965 // executable module, it will clear the targets module list, and if we
966 // have an in memory dyld module, it will get removed from the list so
967 // we will need to add it back after setting the executable module, so
968 // we first try and see if we already have a weak pointer to the dyld
969 // module, make it into a shared pointer, then add the executable, then
970 // re-add it back to make sure it is always in the list.
971 ModuleSP dyld_module_sp(GetDYLDModule());
972
973 m_process->GetTarget().SetExecutableModule(exe_module_sp,
974 eLoadDependentsNo);
975
976 if (dyld_module_sp) {
977 if (target.GetImages().AppendIfNeeded(dyld_module_sp)) {
978 std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
979
980 // Also add it to the section list.
981 UpdateImageLoadAddress(dyld_module_sp.get(), m_dyld);
982 }
983 }
984 }
985 }
986 }
987 }
988
989 // Dump the _dyld_all_image_infos members and all current image infos that we
990 // have parsed to the file handle provided.
PutToLog(Log * log) const991 void DynamicLoaderMacOSXDYLD::PutToLog(Log *log) const {
992 if (log == nullptr)
993 return;
994
995 std::lock_guard<std::recursive_mutex> guard(m_mutex);
996 std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
997 LLDB_LOGF(log,
998 "dyld_all_image_infos = { version=%d, count=%d, addr=0x%8.8" PRIx64
999 ", notify=0x%8.8" PRIx64 " }",
1000 m_dyld_all_image_infos.version,
1001 m_dyld_all_image_infos.dylib_info_count,
1002 (uint64_t)m_dyld_all_image_infos.dylib_info_addr,
1003 (uint64_t)m_dyld_all_image_infos.notification);
1004 size_t i;
1005 const size_t count = m_dyld_image_infos.size();
1006 if (count > 0) {
1007 log->PutCString("Loaded:");
1008 for (i = 0; i < count; i++)
1009 m_dyld_image_infos[i].PutToLog(log);
1010 }
1011 }
1012
SetNotificationBreakpoint()1013 bool DynamicLoaderMacOSXDYLD::SetNotificationBreakpoint() {
1014 DEBUG_PRINTF("DynamicLoaderMacOSXDYLD::%s() process state = %s\n",
1015 __FUNCTION__, StateAsCString(m_process->GetState()));
1016 if (m_break_id == LLDB_INVALID_BREAK_ID) {
1017 if (m_dyld_all_image_infos.notification != LLDB_INVALID_ADDRESS) {
1018 Address so_addr;
1019 // Set the notification breakpoint and install a breakpoint callback
1020 // function that will get called each time the breakpoint gets hit. We
1021 // will use this to track when shared libraries get loaded/unloaded.
1022 bool resolved = m_process->GetTarget().ResolveLoadAddress(
1023 m_dyld_all_image_infos.notification, so_addr);
1024 if (!resolved) {
1025 ModuleSP dyld_module_sp = GetDYLDModule();
1026 if (dyld_module_sp) {
1027 std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
1028
1029 UpdateImageLoadAddress(dyld_module_sp.get(), m_dyld);
1030 resolved = m_process->GetTarget().ResolveLoadAddress(
1031 m_dyld_all_image_infos.notification, so_addr);
1032 }
1033 }
1034
1035 if (resolved) {
1036 Breakpoint *dyld_break =
1037 m_process->GetTarget().CreateBreakpoint(so_addr, true, false).get();
1038 dyld_break->SetCallback(DynamicLoaderMacOSXDYLD::NotifyBreakpointHit,
1039 this, true);
1040 dyld_break->SetBreakpointKind("shared-library-event");
1041 m_break_id = dyld_break->GetID();
1042 }
1043 }
1044 }
1045 return m_break_id != LLDB_INVALID_BREAK_ID;
1046 }
1047
CanLoadImage()1048 Status DynamicLoaderMacOSXDYLD::CanLoadImage() {
1049 Status error;
1050 // In order for us to tell if we can load a shared library we verify that the
1051 // dylib_info_addr isn't zero (which means no shared libraries have been set
1052 // yet, or dyld is currently mucking with the shared library list).
1053 if (ReadAllImageInfosStructure()) {
1054 // TODO: also check the _dyld_global_lock_held variable in
1055 // libSystem.B.dylib?
1056 // TODO: check the malloc lock?
1057 // TODO: check the objective C lock?
1058 if (m_dyld_all_image_infos.dylib_info_addr != 0)
1059 return error; // Success
1060 }
1061
1062 error.SetErrorString("unsafe to load or unload shared libraries");
1063 return error;
1064 }
1065
GetSharedCacheInformation(lldb::addr_t & base_address,UUID & uuid,LazyBool & using_shared_cache,LazyBool & private_shared_cache)1066 bool DynamicLoaderMacOSXDYLD::GetSharedCacheInformation(
1067 lldb::addr_t &base_address, UUID &uuid, LazyBool &using_shared_cache,
1068 LazyBool &private_shared_cache) {
1069 base_address = LLDB_INVALID_ADDRESS;
1070 uuid.Clear();
1071 using_shared_cache = eLazyBoolCalculate;
1072 private_shared_cache = eLazyBoolCalculate;
1073
1074 if (m_process) {
1075 addr_t all_image_infos = m_process->GetImageInfoAddress();
1076
1077 // The address returned by GetImageInfoAddress may be the address of dyld
1078 // (don't want) or it may be the address of the dyld_all_image_infos
1079 // structure (want). The first four bytes will be either the version field
1080 // (all_image_infos) or a Mach-O file magic constant. Version 13 and higher
1081 // of dyld_all_image_infos is required to get the sharedCacheUUID field.
1082
1083 Status err;
1084 uint32_t version_or_magic =
1085 m_process->ReadUnsignedIntegerFromMemory(all_image_infos, 4, -1, err);
1086 if (version_or_magic != static_cast<uint32_t>(-1) &&
1087 version_or_magic != llvm::MachO::MH_MAGIC &&
1088 version_or_magic != llvm::MachO::MH_CIGAM &&
1089 version_or_magic != llvm::MachO::MH_MAGIC_64 &&
1090 version_or_magic != llvm::MachO::MH_CIGAM_64 &&
1091 version_or_magic >= 13) {
1092 addr_t sharedCacheUUID_address = LLDB_INVALID_ADDRESS;
1093 int wordsize = m_process->GetAddressByteSize();
1094 if (wordsize == 8) {
1095 sharedCacheUUID_address =
1096 all_image_infos + 160; // sharedCacheUUID <mach-o/dyld_images.h>
1097 }
1098 if (wordsize == 4) {
1099 sharedCacheUUID_address =
1100 all_image_infos + 84; // sharedCacheUUID <mach-o/dyld_images.h>
1101 }
1102 if (sharedCacheUUID_address != LLDB_INVALID_ADDRESS) {
1103 uuid_t shared_cache_uuid;
1104 if (m_process->ReadMemory(sharedCacheUUID_address, shared_cache_uuid,
1105 sizeof(uuid_t), err) == sizeof(uuid_t)) {
1106 uuid = UUID(shared_cache_uuid, 16);
1107 if (uuid.IsValid()) {
1108 using_shared_cache = eLazyBoolYes;
1109 }
1110 }
1111
1112 if (version_or_magic >= 15) {
1113 // The sharedCacheBaseAddress field is the next one in the
1114 // dyld_all_image_infos struct.
1115 addr_t sharedCacheBaseAddr_address = sharedCacheUUID_address + 16;
1116 Status error;
1117 base_address = m_process->ReadUnsignedIntegerFromMemory(
1118 sharedCacheBaseAddr_address, wordsize, LLDB_INVALID_ADDRESS,
1119 error);
1120 if (error.Fail())
1121 base_address = LLDB_INVALID_ADDRESS;
1122 }
1123
1124 return true;
1125 }
1126
1127 //
1128 // add
1129 // NB: sharedCacheBaseAddress is the next field in dyld_all_image_infos
1130 // after
1131 // sharedCacheUUID -- that is, 16 bytes after it, if we wanted to fetch
1132 // it.
1133 }
1134 }
1135 return false;
1136 }
1137
IsFullyInitialized()1138 bool DynamicLoaderMacOSXDYLD::IsFullyInitialized() {
1139 if (ReadAllImageInfosStructure())
1140 return m_dyld_all_image_infos.libSystemInitialized;
1141 return false;
1142 }
1143
Initialize()1144 void DynamicLoaderMacOSXDYLD::Initialize() {
1145 PluginManager::RegisterPlugin(GetPluginNameStatic(),
1146 GetPluginDescriptionStatic(), CreateInstance);
1147 DynamicLoaderMacOS::Initialize();
1148 }
1149
Terminate()1150 void DynamicLoaderMacOSXDYLD::Terminate() {
1151 DynamicLoaderMacOS::Terminate();
1152 PluginManager::UnregisterPlugin(CreateInstance);
1153 }
1154
GetPluginDescriptionStatic()1155 llvm::StringRef DynamicLoaderMacOSXDYLD::GetPluginDescriptionStatic() {
1156 return "Dynamic loader plug-in that watches for shared library loads/unloads "
1157 "in MacOSX user processes.";
1158 }
1159
AddrByteSize()1160 uint32_t DynamicLoaderMacOSXDYLD::AddrByteSize() {
1161 std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
1162
1163 switch (m_dyld.header.magic) {
1164 case llvm::MachO::MH_MAGIC:
1165 case llvm::MachO::MH_CIGAM:
1166 return 4;
1167
1168 case llvm::MachO::MH_MAGIC_64:
1169 case llvm::MachO::MH_CIGAM_64:
1170 return 8;
1171
1172 default:
1173 break;
1174 }
1175 return 0;
1176 }
1177
GetByteOrderFromMagic(uint32_t magic)1178 lldb::ByteOrder DynamicLoaderMacOSXDYLD::GetByteOrderFromMagic(uint32_t magic) {
1179 switch (magic) {
1180 case llvm::MachO::MH_MAGIC:
1181 case llvm::MachO::MH_MAGIC_64:
1182 return endian::InlHostByteOrder();
1183
1184 case llvm::MachO::MH_CIGAM:
1185 case llvm::MachO::MH_CIGAM_64:
1186 if (endian::InlHostByteOrder() == lldb::eByteOrderBig)
1187 return lldb::eByteOrderLittle;
1188 else
1189 return lldb::eByteOrderBig;
1190
1191 default:
1192 break;
1193 }
1194 return lldb::eByteOrderInvalid;
1195 }
1196