1 //===-- DynamicLoaderDarwinKernel.cpp -----------------------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "lldb/lldb-python.h"
11
12 #include "lldb/Breakpoint/StoppointCallbackContext.h"
13 #include "lldb/Core/DataBuffer.h"
14 #include "lldb/Core/DataBufferHeap.h"
15 #include "lldb/Core/Debugger.h"
16 #include "lldb/Core/Log.h"
17 #include "lldb/Core/Module.h"
18 #include "lldb/Core/ModuleSpec.h"
19 #include "lldb/Core/PluginManager.h"
20 #include "lldb/Core/Section.h"
21 #include "lldb/Core/State.h"
22 #include "lldb/Host/Symbols.h"
23 #include "lldb/Symbol/ObjectFile.h"
24 #include "lldb/Target/RegisterContext.h"
25 #include "lldb/Target/StackFrame.h"
26 #include "lldb/Target/Target.h"
27 #include "lldb/Target/Thread.h"
28 #include "lldb/Target/ThreadPlanRunToAddress.h"
29 #include "Plugins/Platform/MacOSX/PlatformDarwinKernel.h"
30
31 #include "DynamicLoaderDarwinKernel.h"
32
33 //#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN
34 #ifdef ENABLE_DEBUG_PRINTF
35 #include <stdio.h>
36 #define DEBUG_PRINTF(fmt, ...) printf(fmt, ## __VA_ARGS__)
37 #else
38 #define DEBUG_PRINTF(fmt, ...)
39 #endif
40
41 using namespace lldb;
42 using namespace lldb_private;
43
44 // Progressively greater amounts of scanning we will allow
45 // For some targets very early in startup, we can't do any random reads of memory or we can crash the device
46 // so a setting is needed that can completely disable the KASLR scans.
47
48 enum KASLRScanType
49 {
50 eKASLRScanNone = 0, // No reading into the inferior at all
51 eKASLRScanLowgloAddresses, // Check one word of memory for a possible kernel addr, then see if a kernel is there
52 eKASLRScanNearPC, // Scan backwards from the current $pc looking for kernel; checking at 96 locations total
53 eKASLRScanExhaustiveScan // Scan through the entire possible kernel address range looking for a kernel
54 };
55
56 OptionEnumValueElement
57 g_kaslr_kernel_scan_enum_values[] =
58 {
59 { eKASLRScanNone, "none", "Do not read memory looking for a Darwin kernel when attaching." },
60 { eKASLRScanLowgloAddresses, "basic", "Check for the Darwin kernel's load addr in the lowglo page (boot-args=debug) only." },
61 { eKASLRScanNearPC, "fast-scan", "Scan near the pc value on attach to find the Darwin kernel's load address."},
62 { eKASLRScanExhaustiveScan, "exhaustive-scan", "Scan through the entire potential address range of Darwin kernel (only on 32-bit targets)."},
63 { 0, NULL, NULL }
64 };
65
66 static PropertyDefinition
67 g_properties[] =
68 {
69 { "load-kexts" , OptionValue::eTypeBoolean, true, true, NULL, NULL, "Automatically loads kext images when attaching to a kernel." },
70 { "scan-type", OptionValue::eTypeEnum, true, eKASLRScanNearPC, NULL, g_kaslr_kernel_scan_enum_values, "Control how many reads lldb will make while searching for a Darwin kernel on attach." },
71 { NULL , OptionValue::eTypeInvalid, false, 0 , NULL, NULL, NULL }
72 };
73
74 enum {
75 ePropertyLoadKexts,
76 ePropertyScanType
77 };
78
79 class DynamicLoaderDarwinKernelProperties : public Properties
80 {
81 public:
82
83 static ConstString &
GetSettingName()84 GetSettingName ()
85 {
86 static ConstString g_setting_name("darwin-kernel");
87 return g_setting_name;
88 }
89
DynamicLoaderDarwinKernelProperties()90 DynamicLoaderDarwinKernelProperties() :
91 Properties ()
92 {
93 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
94 m_collection_sp->Initialize(g_properties);
95 }
96
97 virtual
~DynamicLoaderDarwinKernelProperties()98 ~DynamicLoaderDarwinKernelProperties()
99 {
100 }
101
102 bool
GetLoadKexts() const103 GetLoadKexts() const
104 {
105 const uint32_t idx = ePropertyLoadKexts;
106 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
107 }
108
109 KASLRScanType
GetScanType() const110 GetScanType() const
111 {
112 const uint32_t idx = ePropertyScanType;
113 return (KASLRScanType) m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
114 }
115
116
117 };
118
119 typedef std::shared_ptr<DynamicLoaderDarwinKernelProperties> DynamicLoaderDarwinKernelPropertiesSP;
120
121 static const DynamicLoaderDarwinKernelPropertiesSP &
GetGlobalProperties()122 GetGlobalProperties()
123 {
124 static DynamicLoaderDarwinKernelPropertiesSP g_settings_sp;
125 if (!g_settings_sp)
126 g_settings_sp.reset (new DynamicLoaderDarwinKernelProperties ());
127 return g_settings_sp;
128 }
129
130 //----------------------------------------------------------------------
131 // Create an instance of this class. This function is filled into
132 // the plugin info class that gets handed out by the plugin factory and
133 // allows the lldb to instantiate an instance of this class.
134 //----------------------------------------------------------------------
135 DynamicLoader *
CreateInstance(Process * process,bool force)136 DynamicLoaderDarwinKernel::CreateInstance (Process* process, bool force)
137 {
138 if (!force)
139 {
140 // If the user provided an executable binary and it is not a kernel,
141 // this plugin should not create an instance.
142 Module* exe_module = process->GetTarget().GetExecutableModulePointer();
143 if (exe_module)
144 {
145 ObjectFile *object_file = exe_module->GetObjectFile();
146 if (object_file)
147 {
148 if (object_file->GetStrata() != ObjectFile::eStrataKernel)
149 {
150 return NULL;
151 }
152 }
153 }
154
155 // If the target's architecture does not look like an Apple environment,
156 // this plugin should not create an instance.
157 const llvm::Triple &triple_ref = process->GetTarget().GetArchitecture().GetTriple();
158 switch (triple_ref.getOS())
159 {
160 case llvm::Triple::Darwin:
161 case llvm::Triple::MacOSX:
162 case llvm::Triple::IOS:
163 if (triple_ref.getVendor() != llvm::Triple::Apple)
164 {
165 return NULL;
166 }
167 break;
168 // If we have triple like armv7-unknown-unknown, we should try looking for a Darwin kernel.
169 case llvm::Triple::UnknownOS:
170 break;
171 default:
172 return NULL;
173 break;
174 }
175 }
176
177 // At this point if there is an ExecutableModule, it is a kernel and the Target is some variant of an Apple system.
178 // If the Process hasn't provided the kernel load address, we need to look around in memory to find it.
179
180 addr_t kernel_load_address = SearchForDarwinKernel (process);
181 if (kernel_load_address != LLDB_INVALID_ADDRESS)
182 {
183 process->SetCanJIT(false);
184 return new DynamicLoaderDarwinKernel (process, kernel_load_address);
185 }
186 return NULL;
187 }
188
189 lldb::addr_t
SearchForDarwinKernel(Process * process)190 DynamicLoaderDarwinKernel::SearchForDarwinKernel (Process *process)
191 {
192 addr_t kernel_load_address = process->GetImageInfoAddress();
193 if (kernel_load_address == LLDB_INVALID_ADDRESS)
194 {
195 kernel_load_address = SearchForKernelAtSameLoadAddr (process);
196 if (kernel_load_address == LLDB_INVALID_ADDRESS)
197 {
198 kernel_load_address = SearchForKernelWithDebugHints (process);
199 if (kernel_load_address == LLDB_INVALID_ADDRESS)
200 {
201 kernel_load_address = SearchForKernelNearPC (process);
202 if (kernel_load_address == LLDB_INVALID_ADDRESS)
203 {
204 kernel_load_address = SearchForKernelViaExhaustiveSearch (process);
205 }
206 }
207 }
208 }
209 return kernel_load_address;
210 }
211
212 //----------------------------------------------------------------------
213 // Check if the kernel binary is loaded in memory without a slide.
214 // First verify that the ExecutableModule is a kernel before we proceed.
215 // Returns the address of the kernel if one was found, else LLDB_INVALID_ADDRESS.
216 //----------------------------------------------------------------------
217 lldb::addr_t
SearchForKernelAtSameLoadAddr(Process * process)218 DynamicLoaderDarwinKernel::SearchForKernelAtSameLoadAddr (Process *process)
219 {
220 Module *exe_module = process->GetTarget().GetExecutableModulePointer();
221 if (exe_module == NULL)
222 return LLDB_INVALID_ADDRESS;
223
224 ObjectFile *exe_objfile = exe_module->GetObjectFile();
225 if (exe_objfile == NULL)
226 return LLDB_INVALID_ADDRESS;
227
228 if (exe_objfile->GetType() != ObjectFile::eTypeExecutable || exe_objfile->GetStrata() != ObjectFile::eStrataKernel)
229 return LLDB_INVALID_ADDRESS;
230
231 if (!exe_objfile->GetHeaderAddress().IsValid())
232 return LLDB_INVALID_ADDRESS;
233
234 if (CheckForKernelImageAtAddress (exe_objfile->GetHeaderAddress().GetFileAddress(), process) == exe_module->GetUUID())
235 return exe_objfile->GetHeaderAddress().GetFileAddress();
236
237 return LLDB_INVALID_ADDRESS;
238 }
239
240 //----------------------------------------------------------------------
241 // If the debug flag is included in the boot-args nvram setting, the kernel's load address
242 // will be noted in the lowglo page at a fixed address
243 // Returns the address of the kernel if one was found, else LLDB_INVALID_ADDRESS.
244 //----------------------------------------------------------------------
245 lldb::addr_t
SearchForKernelWithDebugHints(Process * process)246 DynamicLoaderDarwinKernel::SearchForKernelWithDebugHints (Process *process)
247 {
248 if (GetGlobalProperties()->GetScanType() == eKASLRScanNone)
249 return LLDB_INVALID_ADDRESS;
250
251 Error read_err;
252 addr_t addr = LLDB_INVALID_ADDRESS;
253 if (process->GetTarget().GetArchitecture().GetAddressByteSize() == 8)
254 {
255 addr = process->ReadUnsignedIntegerFromMemory (0xffffff8000002010ULL, 8, LLDB_INVALID_ADDRESS, read_err);
256 }
257 else
258 {
259 addr = process->ReadUnsignedIntegerFromMemory (0xffff0110, 4, LLDB_INVALID_ADDRESS, read_err);
260 }
261
262 if (addr == 0)
263 addr = LLDB_INVALID_ADDRESS;
264
265 if (addr != LLDB_INVALID_ADDRESS)
266 {
267 if (CheckForKernelImageAtAddress (addr, process).IsValid())
268 return addr;
269 }
270
271 return LLDB_INVALID_ADDRESS;
272 }
273
274 //----------------------------------------------------------------------
275 // If the kernel is currently executing when lldb attaches, and we don't have
276 // a better way of finding the kernel's load address, try searching backwards
277 // from the current pc value looking for the kernel's Mach header in memory.
278 // Returns the address of the kernel if one was found, else LLDB_INVALID_ADDRESS.
279 //----------------------------------------------------------------------
280 lldb::addr_t
SearchForKernelNearPC(Process * process)281 DynamicLoaderDarwinKernel::SearchForKernelNearPC (Process *process)
282 {
283 if (GetGlobalProperties()->GetScanType() == eKASLRScanNone
284 || GetGlobalProperties()->GetScanType() == eKASLRScanLowgloAddresses)
285 {
286 return LLDB_INVALID_ADDRESS;
287 }
288
289 ThreadSP thread = process->GetThreadList().GetSelectedThread ();
290 if (thread.get() == NULL)
291 return LLDB_INVALID_ADDRESS;
292 addr_t pc = thread->GetRegisterContext ()->GetPC(LLDB_INVALID_ADDRESS);
293
294 if (pc == LLDB_INVALID_ADDRESS)
295 return LLDB_INVALID_ADDRESS;
296
297 addr_t kernel_range_low;
298 if (process->GetTarget().GetArchitecture().GetAddressByteSize() == 8)
299 {
300 kernel_range_low = 1ULL << 63;
301 }
302 else
303 {
304 kernel_range_low = 1ULL << 31;
305 }
306
307 // Outside the normal kernel address range, this is probably userland code running right now
308 if (pc < kernel_range_low)
309 return LLDB_INVALID_ADDRESS;
310
311 // The kernel will load at at one megabyte boundary (0x100000), or at that boundary plus
312 // an offset of one page (0x1000) or two, depending on the device.
313
314 // Round the current pc down to the nearest one megabyte boundary - the place where we will start searching.
315 addr_t addr = pc & ~0xfffff;
316
317 int i = 0;
318 while (i < 32 && pc >= kernel_range_low)
319 {
320 if (CheckForKernelImageAtAddress (addr, process).IsValid())
321 return addr;
322 if (CheckForKernelImageAtAddress (addr + 0x1000, process).IsValid())
323 return addr + 0x1000;
324 if (CheckForKernelImageAtAddress (addr + 0x2000, process).IsValid())
325 return addr + 0x2000;
326 i++;
327 addr -= 0x100000;
328 }
329
330 return LLDB_INVALID_ADDRESS;
331 }
332
333 //----------------------------------------------------------------------
334 // Scan through the valid address range for a kernel binary.
335 // This is uselessly slow in 64-bit environments so we don't even try it.
336 // This scan is not enabled by default even for 32-bit targets.
337 // Returns the address of the kernel if one was found, else LLDB_INVALID_ADDRESS.
338 //----------------------------------------------------------------------
339 lldb::addr_t
SearchForKernelViaExhaustiveSearch(Process * process)340 DynamicLoaderDarwinKernel::SearchForKernelViaExhaustiveSearch (Process *process)
341 {
342 if (GetGlobalProperties()->GetScanType() != eKASLRScanExhaustiveScan)
343 {
344 return LLDB_INVALID_ADDRESS;
345 }
346
347 addr_t kernel_range_low, kernel_range_high;
348 if (process->GetTarget().GetArchitecture().GetAddressByteSize() == 8)
349 {
350 kernel_range_low = 1ULL << 63;
351 kernel_range_high = UINT64_MAX;
352 }
353 else
354 {
355 kernel_range_low = 1ULL << 31;
356 kernel_range_high = UINT32_MAX;
357 }
358
359 // Stepping through memory at one-megabyte resolution looking for a kernel
360 // rarely works (fast enough) with a 64-bit address space -- for now, let's
361 // not even bother. We may be attaching to something which *isn't* a kernel
362 // and we don't want to spin for minutes on-end looking for a kernel.
363 if (process->GetTarget().GetArchitecture().GetAddressByteSize() == 8)
364 return LLDB_INVALID_ADDRESS;
365
366 addr_t addr = kernel_range_low;
367
368 while (addr >= kernel_range_low && addr < kernel_range_high)
369 {
370 if (CheckForKernelImageAtAddress (addr, process).IsValid())
371 return addr;
372 if (CheckForKernelImageAtAddress (addr + 0x1000, process).IsValid())
373 return addr + 0x1000;
374 if (CheckForKernelImageAtAddress (addr + 0x2000, process).IsValid())
375 return addr + 0x2000;
376 addr += 0x100000;
377 }
378 return LLDB_INVALID_ADDRESS;
379 }
380
381 //----------------------------------------------------------------------
382 // Given an address in memory, look to see if there is a kernel image at that
383 // address.
384 // Returns a UUID; if a kernel was not found at that address, UUID.IsValid() will be false.
385 //----------------------------------------------------------------------
386 lldb_private::UUID
CheckForKernelImageAtAddress(lldb::addr_t addr,Process * process)387 DynamicLoaderDarwinKernel::CheckForKernelImageAtAddress (lldb::addr_t addr, Process *process)
388 {
389 if (addr == LLDB_INVALID_ADDRESS)
390 return UUID();
391
392 // First try a quick test -- read the first 4 bytes and see if there is a valid Mach-O magic field there
393 // (the first field of the mach_header/mach_header_64 struct).
394
395 Error read_error;
396 uint64_t result = process->ReadUnsignedIntegerFromMemory (addr, 4, LLDB_INVALID_ADDRESS, read_error);
397 if (result != llvm::MachO::HeaderMagic64
398 && result != llvm::MachO::HeaderMagic32
399 && result != llvm::MachO::HeaderMagic32Swapped
400 && result != llvm::MachO::HeaderMagic64Swapped)
401 {
402 return UUID();
403 }
404
405 // Read the mach header and see whether it looks like a kernel
406 llvm::MachO::mach_header header;
407 if (process->DoReadMemory (addr, &header, sizeof(header), read_error) != sizeof(header))
408 return UUID();
409
410 if (header.magic == llvm::MachO::HeaderMagic32Swapped ||
411 header.magic == llvm::MachO::HeaderMagic64Swapped)
412 {
413 header.magic = llvm::ByteSwap_32(header.magic);
414 header.cputype = llvm::ByteSwap_32(header.cputype);
415 header.cpusubtype = llvm::ByteSwap_32(header.cpusubtype);
416 header.filetype = llvm::ByteSwap_32(header.filetype);
417 header.ncmds = llvm::ByteSwap_32(header.ncmds);
418 header.sizeofcmds = llvm::ByteSwap_32(header.sizeofcmds);
419 header.flags = llvm::ByteSwap_32(header.flags);
420 }
421
422 // A kernel is an executable which does not have the dynamic link object flag set.
423 if (header.filetype == llvm::MachO::HeaderFileTypeExecutable
424 && (header.flags & llvm::MachO::HeaderFlagBitIsDynamicLinkObject) == 0)
425 {
426 // Create a full module to get the UUID
427 ModuleSP memory_module_sp = process->ReadModuleFromMemory (FileSpec ("temp_mach_kernel", false), addr);
428 if (!memory_module_sp.get())
429 return UUID();
430
431 ObjectFile *exe_objfile = memory_module_sp->GetObjectFile();
432 if (exe_objfile == NULL)
433 return UUID();
434
435 if (exe_objfile->GetType() == ObjectFile::eTypeExecutable && exe_objfile->GetStrata() == ObjectFile::eStrataKernel)
436 {
437 ArchSpec kernel_arch (eArchTypeMachO, header.cputype, header.cpusubtype);
438 if (!process->GetTarget().GetArchitecture().IsCompatibleMatch(kernel_arch))
439 {
440 process->GetTarget().SetArchitecture (kernel_arch);
441 }
442 return memory_module_sp->GetUUID();
443 }
444 }
445
446 return UUID();
447 }
448
449 //----------------------------------------------------------------------
450 // Constructor
451 //----------------------------------------------------------------------
DynamicLoaderDarwinKernel(Process * process,lldb::addr_t kernel_addr)452 DynamicLoaderDarwinKernel::DynamicLoaderDarwinKernel (Process* process, lldb::addr_t kernel_addr) :
453 DynamicLoader(process),
454 m_kernel_load_address (kernel_addr),
455 m_kernel(),
456 m_kext_summary_header_ptr_addr (),
457 m_kext_summary_header_addr (),
458 m_kext_summary_header (),
459 m_known_kexts (),
460 m_mutex(Mutex::eMutexTypeRecursive),
461 m_break_id (LLDB_INVALID_BREAK_ID)
462 {
463 PlatformSP platform_sp(Platform::FindPlugin (process, PlatformDarwinKernel::GetPluginNameStatic ()));
464 // Only select the darwin-kernel Platform if we've been asked to load kexts.
465 // It can take some time to scan over all of the kext info.plists and that
466 // shouldn't be done if kext loading is explicitly disabled.
467 if (platform_sp.get() && GetGlobalProperties()->GetLoadKexts())
468 {
469 process->GetTarget().SetPlatform (platform_sp);
470 }
471 }
472
473 //----------------------------------------------------------------------
474 // Destructor
475 //----------------------------------------------------------------------
~DynamicLoaderDarwinKernel()476 DynamicLoaderDarwinKernel::~DynamicLoaderDarwinKernel()
477 {
478 Clear(true);
479 }
480
481 void
UpdateIfNeeded()482 DynamicLoaderDarwinKernel::UpdateIfNeeded()
483 {
484 LoadKernelModuleIfNeeded();
485 SetNotificationBreakpointIfNeeded ();
486 }
487 //------------------------------------------------------------------
488 /// Called after attaching a process.
489 ///
490 /// Allow DynamicLoader plug-ins to execute some code after
491 /// attaching to a process.
492 //------------------------------------------------------------------
493 void
DidAttach()494 DynamicLoaderDarwinKernel::DidAttach ()
495 {
496 PrivateInitialize(m_process);
497 UpdateIfNeeded();
498 }
499
500 //------------------------------------------------------------------
501 /// Called after attaching a process.
502 ///
503 /// Allow DynamicLoader plug-ins to execute some code after
504 /// attaching to a process.
505 //------------------------------------------------------------------
506 void
DidLaunch()507 DynamicLoaderDarwinKernel::DidLaunch ()
508 {
509 PrivateInitialize(m_process);
510 UpdateIfNeeded();
511 }
512
513
514 //----------------------------------------------------------------------
515 // Clear out the state of this class.
516 //----------------------------------------------------------------------
517 void
Clear(bool clear_process)518 DynamicLoaderDarwinKernel::Clear (bool clear_process)
519 {
520 Mutex::Locker locker(m_mutex);
521
522 if (m_process->IsAlive() && LLDB_BREAK_ID_IS_VALID(m_break_id))
523 m_process->ClearBreakpointSiteByID(m_break_id);
524
525 if (clear_process)
526 m_process = NULL;
527 m_kernel.Clear();
528 m_known_kexts.clear();
529 m_kext_summary_header_ptr_addr.Clear();
530 m_kext_summary_header_addr.Clear();
531 m_break_id = LLDB_INVALID_BREAK_ID;
532 }
533
534
535 bool
LoadImageAtFileAddress(Process * process)536 DynamicLoaderDarwinKernel::KextImageInfo::LoadImageAtFileAddress (Process *process)
537 {
538 if (IsLoaded())
539 return true;
540
541 if (m_module_sp)
542 {
543 bool changed = false;
544 if (m_module_sp->SetLoadAddress (process->GetTarget(), 0, changed))
545 m_load_process_stop_id = process->GetStopID();
546 }
547 return false;
548 }
549
550 void
SetModule(ModuleSP module_sp)551 DynamicLoaderDarwinKernel::KextImageInfo::SetModule (ModuleSP module_sp)
552 {
553 m_module_sp = module_sp;
554 if (module_sp.get() && module_sp->GetObjectFile())
555 {
556 if (module_sp->GetObjectFile()->GetType() == ObjectFile::eTypeExecutable
557 && module_sp->GetObjectFile()->GetStrata() == ObjectFile::eStrataKernel)
558 {
559 m_kernel_image = true;
560 }
561 else
562 {
563 m_kernel_image = false;
564 }
565 }
566 }
567
568 ModuleSP
GetModule()569 DynamicLoaderDarwinKernel::KextImageInfo::GetModule ()
570 {
571 return m_module_sp;
572 }
573
574 void
SetLoadAddress(addr_t load_addr)575 DynamicLoaderDarwinKernel::KextImageInfo::SetLoadAddress (addr_t load_addr)
576 {
577 m_load_address = load_addr;
578 }
579
580 addr_t
GetLoadAddress() const581 DynamicLoaderDarwinKernel::KextImageInfo::GetLoadAddress () const
582 {
583 return m_load_address;
584 }
585
586 uint64_t
GetSize() const587 DynamicLoaderDarwinKernel::KextImageInfo::GetSize () const
588 {
589 return m_size;
590 }
591
592 void
SetSize(uint64_t size)593 DynamicLoaderDarwinKernel::KextImageInfo::SetSize (uint64_t size)
594 {
595 m_size = size;
596 }
597
598 uint32_t
GetProcessStopId() const599 DynamicLoaderDarwinKernel::KextImageInfo::GetProcessStopId () const
600 {
601 return m_load_process_stop_id;
602 }
603
604 void
SetProcessStopId(uint32_t stop_id)605 DynamicLoaderDarwinKernel::KextImageInfo::SetProcessStopId (uint32_t stop_id)
606 {
607 m_load_process_stop_id = stop_id;
608 }
609
610 bool
operator ==(const KextImageInfo & rhs)611 DynamicLoaderDarwinKernel::KextImageInfo::operator== (const KextImageInfo &rhs)
612 {
613 if (m_uuid.IsValid() || rhs.GetUUID().IsValid())
614 {
615 if (m_uuid == rhs.GetUUID())
616 {
617 return true;
618 }
619 return false;
620 }
621
622 if (m_name == rhs.GetName() && m_load_address == rhs.GetLoadAddress())
623 return true;
624
625 return false;
626 }
627
628 void
SetName(const char * name)629 DynamicLoaderDarwinKernel::KextImageInfo::SetName (const char *name)
630 {
631 m_name = name;
632 }
633
634 std::string
GetName() const635 DynamicLoaderDarwinKernel::KextImageInfo::GetName () const
636 {
637 return m_name;
638 }
639
640 void
SetUUID(const UUID & uuid)641 DynamicLoaderDarwinKernel::KextImageInfo::SetUUID (const UUID &uuid)
642 {
643 m_uuid = uuid;
644 }
645
646 UUID
GetUUID() const647 DynamicLoaderDarwinKernel::KextImageInfo::GetUUID () const
648 {
649 return m_uuid;
650 }
651
652 // Given the m_load_address from the kext summaries, and a UUID, try to create an in-memory
653 // Module at that address. Require that the MemoryModule have a matching UUID and detect
654 // if this MemoryModule is a kernel or a kext.
655 //
656 // Returns true if m_memory_module_sp is now set to a valid Module.
657
658 bool
ReadMemoryModule(Process * process)659 DynamicLoaderDarwinKernel::KextImageInfo::ReadMemoryModule (Process *process)
660 {
661 if (m_memory_module_sp.get() != NULL)
662 return true;
663 if (m_load_address == LLDB_INVALID_ADDRESS)
664 return false;
665
666 FileSpec file_spec;
667 file_spec.SetFile (m_name.c_str(), false);
668
669 ModuleSP memory_module_sp = process->ReadModuleFromMemory (file_spec, m_load_address);
670
671 if (memory_module_sp.get() == NULL)
672 return false;
673
674 bool is_kernel = false;
675 if (memory_module_sp->GetObjectFile())
676 {
677 if (memory_module_sp->GetObjectFile()->GetType() == ObjectFile::eTypeExecutable
678 && memory_module_sp->GetObjectFile()->GetStrata() == ObjectFile::eStrataKernel)
679 {
680 is_kernel = true;
681 }
682 else if (memory_module_sp->GetObjectFile()->GetType() == ObjectFile::eTypeSharedLibrary)
683 {
684 is_kernel = false;
685 }
686 }
687
688 // If this is a kext, and the kernel specified what UUID we should find at this
689 // load address, require that the memory module have a matching UUID or something
690 // has gone wrong and we should discard it.
691 if (m_uuid.IsValid())
692 {
693 if (m_uuid != memory_module_sp->GetUUID())
694 {
695 return false;
696 }
697 }
698
699 // If the in-memory Module has a UUID, let's use that.
700 if (!m_uuid.IsValid() && memory_module_sp->GetUUID().IsValid())
701 {
702 m_uuid = memory_module_sp->GetUUID();
703 }
704
705 m_memory_module_sp = memory_module_sp;
706 m_kernel_image = is_kernel;
707 if (is_kernel)
708 {
709 if (memory_module_sp->GetArchitecture().IsValid())
710 {
711 process->GetTarget().SetArchitecture(memory_module_sp->GetArchitecture());
712 }
713 if (m_uuid.IsValid())
714 {
715 Module* exe_module = process->GetTarget().GetExecutableModulePointer();
716 if (exe_module && exe_module->GetUUID().IsValid())
717 {
718 if (m_uuid != exe_module->GetUUID())
719 {
720 Stream *s = &process->GetTarget().GetDebugger().GetOutputStream();
721 if (s)
722 {
723 s->Printf ("warning: Host-side kernel file has Mach-O UUID of %s but remote kernel has a UUID of %s -- a mismatched kernel file will result in a poor debugger experience.\n",
724 exe_module->GetUUID().GetAsString().c_str(),
725 m_uuid.GetAsString().c_str());
726 s->Flush ();
727 }
728 }
729 }
730 }
731 }
732
733 return true;
734 }
735
736 bool
IsKernel() const737 DynamicLoaderDarwinKernel::KextImageInfo::IsKernel () const
738 {
739 return m_kernel_image == true;
740 }
741
742 void
SetIsKernel(bool is_kernel)743 DynamicLoaderDarwinKernel::KextImageInfo::SetIsKernel (bool is_kernel)
744 {
745 m_kernel_image = is_kernel;
746 }
747
748 bool
LoadImageUsingMemoryModule(Process * process)749 DynamicLoaderDarwinKernel::KextImageInfo::LoadImageUsingMemoryModule (Process *process)
750 {
751 if (IsLoaded())
752 return true;
753
754
755 Target &target = process->GetTarget();
756
757 // If we don't have / can't create a memory module for this kext, don't try to load it - we won't
758 // have the correct segment load addresses.
759 if (!ReadMemoryModule (process))
760 {
761 return false;
762 }
763
764 bool uuid_is_valid = m_uuid.IsValid();
765
766 if (IsKernel() && uuid_is_valid && m_memory_module_sp.get())
767 {
768 Stream *s = &target.GetDebugger().GetOutputStream();
769 if (s)
770 {
771 s->Printf ("Kernel UUID: %s\n", m_memory_module_sp->GetUUID().GetAsString().c_str());
772 s->Printf ("Load Address: 0x%" PRIx64 "\n", m_load_address);
773 }
774 }
775
776 if (!m_module_sp)
777 {
778 // See if the kext has already been loaded into the target, probably by the user doing target modules add.
779 const ModuleList &target_images = target.GetImages();
780 m_module_sp = target_images.FindModule(m_uuid);
781
782 // Search for the kext on the local filesystem via the UUID
783 if (!m_module_sp && uuid_is_valid)
784 {
785 ModuleSpec module_spec;
786 module_spec.GetUUID() = m_uuid;
787 module_spec.GetArchitecture() = target.GetArchitecture();
788
789 // For the kernel, we really do need an on-disk file copy of the binary to do anything useful.
790 // This will force a clal to
791 if (IsKernel())
792 {
793 if (Symbols::DownloadObjectAndSymbolFile (module_spec, true))
794 {
795 if (module_spec.GetFileSpec().Exists())
796 {
797 m_module_sp.reset(new Module (module_spec.GetFileSpec(), target.GetArchitecture()));
798 if (m_module_sp.get() && m_module_sp->MatchesModuleSpec (module_spec))
799 {
800 ModuleList loaded_module_list;
801 loaded_module_list.Append (m_module_sp);
802 target.ModulesDidLoad (loaded_module_list);
803 }
804 }
805 }
806 }
807
808 // If the current platform is PlatformDarwinKernel, create a ModuleSpec with the filename set
809 // to be the bundle ID for this kext, e.g. "com.apple.filesystems.msdosfs", and ask the platform
810 // to find it.
811 PlatformSP platform_sp (target.GetPlatform());
812 if (platform_sp)
813 {
814 ConstString platform_name (platform_sp->GetPluginName());
815 static ConstString g_platform_name (PlatformDarwinKernel::GetPluginNameStatic());
816 if (platform_name == g_platform_name)
817 {
818 ModuleSpec kext_bundle_module_spec(module_spec);
819 FileSpec kext_filespec(m_name.c_str(), false);
820 kext_bundle_module_spec.GetFileSpec() = kext_filespec;
821 platform_sp->GetSharedModule (kext_bundle_module_spec, m_module_sp, &target.GetExecutableSearchPaths(), NULL, NULL);
822 }
823 }
824
825 // Ask the Target to find this file on the local system, if possible.
826 // This will search in the list of currently-loaded files, look in the
827 // standard search paths on the system, and on a Mac it will try calling
828 // the DebugSymbols framework with the UUID to find the binary via its
829 // search methods.
830 if (!m_module_sp)
831 {
832 m_module_sp = target.GetSharedModule (module_spec);
833 }
834
835 if (IsKernel() && !m_module_sp)
836 {
837 Stream *s = &target.GetDebugger().GetOutputStream();
838 if (s)
839 {
840 s->Printf ("WARNING: Unable to locate kernel binary on the debugger system.\n");
841 }
842 }
843 }
844
845 // If we managed to find a module, append it to the target's list of images.
846 // If we also have a memory module, require that they have matching UUIDs
847 if (m_module_sp)
848 {
849 bool uuid_match_ok = true;
850 if (m_memory_module_sp)
851 {
852 if (m_module_sp->GetUUID() != m_memory_module_sp->GetUUID())
853 {
854 uuid_match_ok = false;
855 }
856 }
857 if (uuid_match_ok)
858 {
859 target.GetImages().AppendIfNeeded(m_module_sp);
860 if (IsKernel() && target.GetExecutableModulePointer() != m_module_sp.get())
861 {
862 target.SetExecutableModule (m_module_sp, false);
863 }
864 }
865 }
866 }
867
868 if (!m_module_sp && !IsKernel() && m_uuid.IsValid() && !m_name.empty())
869 {
870 Stream *s = &target.GetDebugger().GetOutputStream();
871 if (s)
872 {
873 s->Printf ("warning: Can't find binary/dSYM for %s (%s)\n",
874 m_name.c_str(), m_uuid.GetAsString().c_str());
875 }
876 }
877
878 static ConstString g_section_name_LINKEDIT ("__LINKEDIT");
879
880 if (m_memory_module_sp && m_module_sp)
881 {
882 if (m_module_sp->GetUUID() == m_memory_module_sp->GetUUID())
883 {
884 ObjectFile *ondisk_object_file = m_module_sp->GetObjectFile();
885 ObjectFile *memory_object_file = m_memory_module_sp->GetObjectFile();
886
887 if (memory_object_file && ondisk_object_file)
888 {
889 // The memory_module for kexts may have an invalid __LINKEDIT seg; skip it.
890 const bool ignore_linkedit = !IsKernel ();
891
892 SectionList *ondisk_section_list = ondisk_object_file->GetSectionList ();
893 SectionList *memory_section_list = memory_object_file->GetSectionList ();
894 if (memory_section_list && ondisk_section_list)
895 {
896 const uint32_t num_ondisk_sections = ondisk_section_list->GetSize();
897 // There may be CTF sections in the memory image so we can't
898 // always just compare the number of sections (which are actually
899 // segments in mach-o parlance)
900 uint32_t sect_idx = 0;
901
902 // Use the memory_module's addresses for each section to set the
903 // file module's load address as appropriate. We don't want to use
904 // a single slide value for the entire kext - different segments may
905 // be slid different amounts by the kext loader.
906
907 uint32_t num_sections_loaded = 0;
908 for (sect_idx=0; sect_idx<num_ondisk_sections; ++sect_idx)
909 {
910 SectionSP ondisk_section_sp(ondisk_section_list->GetSectionAtIndex(sect_idx));
911 if (ondisk_section_sp)
912 {
913 // Don't ever load __LINKEDIT as it may or may not be actually
914 // mapped into memory and there is no current way to tell.
915 // I filed rdar://problem/12851706 to track being able to tell
916 // if the __LINKEDIT is actually mapped, but until then, we need
917 // to not load the __LINKEDIT
918 if (ignore_linkedit && ondisk_section_sp->GetName() == g_section_name_LINKEDIT)
919 continue;
920
921 const Section *memory_section = memory_section_list->FindSectionByName(ondisk_section_sp->GetName()).get();
922 if (memory_section)
923 {
924 target.GetSectionLoadList().SetSectionLoadAddress (ondisk_section_sp, memory_section->GetFileAddress());
925 ++num_sections_loaded;
926 }
927 }
928 }
929 if (num_sections_loaded > 0)
930 m_load_process_stop_id = process->GetStopID();
931 else
932 m_module_sp.reset(); // No sections were loaded
933 }
934 else
935 m_module_sp.reset(); // One or both section lists
936 }
937 else
938 m_module_sp.reset(); // One or both object files missing
939 }
940 else
941 m_module_sp.reset(); // UUID mismatch
942 }
943
944 bool is_loaded = IsLoaded();
945
946 if (is_loaded && m_module_sp && IsKernel())
947 {
948 Stream *s = &target.GetDebugger().GetOutputStream();
949 if (s)
950 {
951 ObjectFile *kernel_object_file = m_module_sp->GetObjectFile();
952 if (kernel_object_file)
953 {
954 addr_t file_address = kernel_object_file->GetHeaderAddress().GetFileAddress();
955 if (m_load_address != LLDB_INVALID_ADDRESS && file_address != LLDB_INVALID_ADDRESS)
956 {
957 s->Printf ("Kernel slid 0x%" PRIx64 " in memory.\n", m_load_address - file_address);
958 }
959 }
960 {
961 s->Printf ("Loaded kernel file %s\n",
962 m_module_sp->GetFileSpec().GetPath().c_str());
963 }
964 s->Flush ();
965 }
966 }
967 return is_loaded;
968 }
969
970 uint32_t
GetAddressByteSize()971 DynamicLoaderDarwinKernel::KextImageInfo::GetAddressByteSize ()
972 {
973 if (m_memory_module_sp)
974 return m_memory_module_sp->GetArchitecture().GetAddressByteSize();
975 if (m_module_sp)
976 return m_module_sp->GetArchitecture().GetAddressByteSize();
977 return 0;
978 }
979
980 lldb::ByteOrder
GetByteOrder()981 DynamicLoaderDarwinKernel::KextImageInfo::GetByteOrder()
982 {
983 if (m_memory_module_sp)
984 return m_memory_module_sp->GetArchitecture().GetByteOrder();
985 if (m_module_sp)
986 return m_module_sp->GetArchitecture().GetByteOrder();
987 return lldb::endian::InlHostByteOrder();
988 }
989
990 lldb_private::ArchSpec
GetArchitecture() const991 DynamicLoaderDarwinKernel::KextImageInfo::GetArchitecture () const
992 {
993 if (m_memory_module_sp)
994 return m_memory_module_sp->GetArchitecture();
995 if (m_module_sp)
996 return m_module_sp->GetArchitecture();
997 return lldb_private::ArchSpec ();
998 }
999
1000
1001 //----------------------------------------------------------------------
1002 // Load the kernel module and initialize the "m_kernel" member. Return
1003 // true _only_ if the kernel is loaded the first time through (subsequent
1004 // calls to this function should return false after the kernel has been
1005 // already loaded).
1006 //----------------------------------------------------------------------
1007 void
LoadKernelModuleIfNeeded()1008 DynamicLoaderDarwinKernel::LoadKernelModuleIfNeeded()
1009 {
1010 if (!m_kext_summary_header_ptr_addr.IsValid())
1011 {
1012 m_kernel.Clear();
1013 m_kernel.SetModule (m_process->GetTarget().GetExecutableModule());
1014 m_kernel.SetIsKernel(true);
1015
1016 ConstString kernel_name("mach_kernel");
1017 if (m_kernel.GetModule().get()
1018 && m_kernel.GetModule()->GetObjectFile()
1019 && !m_kernel.GetModule()->GetObjectFile()->GetFileSpec().GetFilename().IsEmpty())
1020 {
1021 kernel_name = m_kernel.GetModule()->GetObjectFile()->GetFileSpec().GetFilename();
1022 }
1023 m_kernel.SetName (kernel_name.AsCString());
1024
1025 if (m_kernel.GetLoadAddress() == LLDB_INVALID_ADDRESS)
1026 {
1027 m_kernel.SetLoadAddress(m_kernel_load_address);
1028 if (m_kernel.GetLoadAddress() == LLDB_INVALID_ADDRESS && m_kernel.GetModule())
1029 {
1030 // We didn't get a hint from the process, so we will
1031 // try the kernel at the address that it exists at in
1032 // the file if we have one
1033 ObjectFile *kernel_object_file = m_kernel.GetModule()->GetObjectFile();
1034 if (kernel_object_file)
1035 {
1036 addr_t load_address = kernel_object_file->GetHeaderAddress().GetLoadAddress(&m_process->GetTarget());
1037 addr_t file_address = kernel_object_file->GetHeaderAddress().GetFileAddress();
1038 if (load_address != LLDB_INVALID_ADDRESS && load_address != 0)
1039 {
1040 m_kernel.SetLoadAddress (load_address);
1041 if (load_address != file_address)
1042 {
1043 // Don't accidentally relocate the kernel to the File address --
1044 // the Load address has already been set to its actual in-memory address.
1045 // Mark it as IsLoaded.
1046 m_kernel.SetProcessStopId (m_process->GetStopID());
1047 }
1048 }
1049 else
1050 {
1051 m_kernel.SetLoadAddress(file_address);
1052 }
1053 }
1054 }
1055 }
1056
1057 if (m_kernel.GetLoadAddress() != LLDB_INVALID_ADDRESS)
1058 {
1059 if (!m_kernel.LoadImageUsingMemoryModule (m_process))
1060 {
1061 m_kernel.LoadImageAtFileAddress (m_process);
1062 }
1063 }
1064
1065 if (m_kernel.IsLoaded() && m_kernel.GetModule())
1066 {
1067 static ConstString kext_summary_symbol ("gLoadedKextSummaries");
1068 const Symbol *symbol = m_kernel.GetModule()->FindFirstSymbolWithNameAndType (kext_summary_symbol, eSymbolTypeData);
1069 if (symbol)
1070 {
1071 m_kext_summary_header_ptr_addr = symbol->GetAddress();
1072 // Update all image infos
1073 ReadAllKextSummaries ();
1074 }
1075 }
1076 else
1077 {
1078 m_kernel.Clear();
1079 }
1080 }
1081 }
1082
1083 //----------------------------------------------------------------------
1084 // Static callback function that gets called when our DYLD notification
1085 // breakpoint gets hit. We update all of our image infos and then
1086 // let our super class DynamicLoader class decide if we should stop
1087 // or not (based on global preference).
1088 //----------------------------------------------------------------------
1089 bool
BreakpointHitCallback(void * baton,StoppointCallbackContext * context,user_id_t break_id,user_id_t break_loc_id)1090 DynamicLoaderDarwinKernel::BreakpointHitCallback (void *baton,
1091 StoppointCallbackContext *context,
1092 user_id_t break_id,
1093 user_id_t break_loc_id)
1094 {
1095 return static_cast<DynamicLoaderDarwinKernel*>(baton)->BreakpointHit (context, break_id, break_loc_id);
1096 }
1097
1098 bool
BreakpointHit(StoppointCallbackContext * context,user_id_t break_id,user_id_t break_loc_id)1099 DynamicLoaderDarwinKernel::BreakpointHit (StoppointCallbackContext *context,
1100 user_id_t break_id,
1101 user_id_t break_loc_id)
1102 {
1103 Log *log(GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
1104 if (log)
1105 log->Printf ("DynamicLoaderDarwinKernel::BreakpointHit (...)\n");
1106
1107 ReadAllKextSummaries ();
1108
1109 if (log)
1110 PutToLog(log);
1111
1112 return GetStopWhenImagesChange();
1113 }
1114
1115
1116 bool
ReadKextSummaryHeader()1117 DynamicLoaderDarwinKernel::ReadKextSummaryHeader ()
1118 {
1119 Mutex::Locker locker(m_mutex);
1120
1121 // the all image infos is already valid for this process stop ID
1122
1123 if (m_kext_summary_header_ptr_addr.IsValid())
1124 {
1125 const uint32_t addr_size = m_kernel.GetAddressByteSize ();
1126 const ByteOrder byte_order = m_kernel.GetByteOrder();
1127 Error error;
1128 // Read enough bytes for a "OSKextLoadedKextSummaryHeader" structure
1129 // which is currenty 4 uint32_t and a pointer.
1130 uint8_t buf[24];
1131 DataExtractor data (buf, sizeof(buf), byte_order, addr_size);
1132 const size_t count = 4 * sizeof(uint32_t) + addr_size;
1133 const bool prefer_file_cache = false;
1134 if (m_process->GetTarget().ReadPointerFromMemory (m_kext_summary_header_ptr_addr,
1135 prefer_file_cache,
1136 error,
1137 m_kext_summary_header_addr))
1138 {
1139 // We got a valid address for our kext summary header and make sure it isn't NULL
1140 if (m_kext_summary_header_addr.IsValid() &&
1141 m_kext_summary_header_addr.GetFileAddress() != 0)
1142 {
1143 const size_t bytes_read = m_process->GetTarget().ReadMemory (m_kext_summary_header_addr, prefer_file_cache, buf, count, error);
1144 if (bytes_read == count)
1145 {
1146 lldb::offset_t offset = 0;
1147 m_kext_summary_header.version = data.GetU32(&offset);
1148 if (m_kext_summary_header.version >= 2)
1149 {
1150 m_kext_summary_header.entry_size = data.GetU32(&offset);
1151 }
1152 else
1153 {
1154 // Versions less than 2 didn't have an entry size, it was hard coded
1155 m_kext_summary_header.entry_size = KERNEL_MODULE_ENTRY_SIZE_VERSION_1;
1156 }
1157 m_kext_summary_header.entry_count = data.GetU32(&offset);
1158 return true;
1159 }
1160 }
1161 }
1162 }
1163 m_kext_summary_header_addr.Clear();
1164 return false;
1165 }
1166
1167 // We've either (a) just attached to a new kernel, or (b) the kexts-changed breakpoint was hit
1168 // and we need to figure out what kexts have been added or removed.
1169 // Read the kext summaries from the inferior kernel memory, compare them against the
1170 // m_known_kexts vector and update the m_known_kexts vector as needed to keep in sync with the
1171 // inferior.
1172
1173 bool
ParseKextSummaries(const Address & kext_summary_addr,uint32_t count)1174 DynamicLoaderDarwinKernel::ParseKextSummaries (const Address &kext_summary_addr, uint32_t count)
1175 {
1176 KextImageInfo::collection kext_summaries;
1177 Log *log(GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
1178 if (log)
1179 log->Printf ("Kexts-changed breakpoint hit, there are %d kexts currently.\n", count);
1180
1181 Mutex::Locker locker(m_mutex);
1182
1183 if (!ReadKextSummaries (kext_summary_addr, count, kext_summaries))
1184 return false;
1185
1186 // read the plugin.dynamic-loader.darwin-kernel.load-kexts setting -- if the user requested no
1187 // kext loading, don't print any messages about kexts & don't try to read them.
1188 const bool load_kexts = GetGlobalProperties()->GetLoadKexts();
1189
1190 // By default, all kexts we've loaded in the past are marked as "remove" and all of the kexts
1191 // we just found out about from ReadKextSummaries are marked as "add".
1192 std::vector<bool> to_be_removed(m_known_kexts.size(), true);
1193 std::vector<bool> to_be_added(count, true);
1194
1195 int number_of_new_kexts_being_added = 0;
1196 int number_of_old_kexts_being_removed = m_known_kexts.size();
1197
1198 const uint32_t new_kexts_size = kext_summaries.size();
1199 const uint32_t old_kexts_size = m_known_kexts.size();
1200
1201 // The m_known_kexts vector may have entries that have been Cleared,
1202 // or are a kernel.
1203 for (uint32_t old_kext = 0; old_kext < old_kexts_size; old_kext++)
1204 {
1205 bool ignore = false;
1206 KextImageInfo &image_info = m_known_kexts[old_kext];
1207 if (image_info.IsKernel())
1208 {
1209 ignore = true;
1210 }
1211 else if (image_info.GetLoadAddress() == LLDB_INVALID_ADDRESS && !image_info.GetModule())
1212 {
1213 ignore = true;
1214 }
1215
1216 if (ignore)
1217 {
1218 number_of_old_kexts_being_removed--;
1219 to_be_removed[old_kext] = false;
1220 }
1221 }
1222
1223 // Scan over the list of kexts we just read from the kernel, note those that
1224 // need to be added and those already loaded.
1225 for (uint32_t new_kext = 0; new_kext < new_kexts_size; new_kext++)
1226 {
1227 bool add_this_one = true;
1228 for (uint32_t old_kext = 0; old_kext < old_kexts_size; old_kext++)
1229 {
1230 if (m_known_kexts[old_kext] == kext_summaries[new_kext])
1231 {
1232 // We already have this kext, don't re-load it.
1233 to_be_added[new_kext] = false;
1234 // This kext is still present, do not remove it.
1235 to_be_removed[old_kext] = false;
1236
1237 number_of_old_kexts_being_removed--;
1238 add_this_one = false;
1239 break;
1240 }
1241 }
1242 if (add_this_one)
1243 {
1244 number_of_new_kexts_being_added++;
1245 }
1246 }
1247
1248 if (number_of_new_kexts_being_added == 0 && number_of_old_kexts_being_removed == 0)
1249 return true;
1250
1251 Stream *s = &m_process->GetTarget().GetDebugger().GetOutputStream();
1252 if (s && load_kexts)
1253 {
1254 if (number_of_new_kexts_being_added > 0 && number_of_old_kexts_being_removed > 0)
1255 {
1256 s->Printf ("Loading %d kext modules and unloading %d kext modules ", number_of_new_kexts_being_added, number_of_old_kexts_being_removed);
1257 }
1258 else if (number_of_new_kexts_being_added > 0)
1259 {
1260 s->Printf ("Loading %d kext modules ", number_of_new_kexts_being_added);
1261 }
1262 else if (number_of_old_kexts_being_removed > 0)
1263 {
1264 s->Printf ("Unloading %d kext modules ", number_of_old_kexts_being_removed);
1265 }
1266 }
1267
1268 if (log)
1269 {
1270 if (load_kexts)
1271 {
1272 log->Printf ("DynamicLoaderDarwinKernel::ParseKextSummaries: %d kexts added, %d kexts removed", number_of_new_kexts_being_added, number_of_old_kexts_being_removed);
1273 }
1274 else
1275 {
1276 log->Printf ("DynamicLoaderDarwinKernel::ParseKextSummaries kext loading is disabled, else would have %d kexts added, %d kexts removed", number_of_new_kexts_being_added, number_of_old_kexts_being_removed);
1277 }
1278 }
1279
1280
1281 if (number_of_new_kexts_being_added > 0)
1282 {
1283 ModuleList loaded_module_list;
1284
1285 const uint32_t num_of_new_kexts = kext_summaries.size();
1286 for (uint32_t new_kext = 0; new_kext < num_of_new_kexts; new_kext++)
1287 {
1288 if (to_be_added[new_kext] == true)
1289 {
1290 KextImageInfo &image_info = kext_summaries[new_kext];
1291 if (load_kexts)
1292 {
1293 if (!image_info.LoadImageUsingMemoryModule (m_process))
1294 {
1295 image_info.LoadImageAtFileAddress (m_process);
1296 }
1297 }
1298
1299 m_known_kexts.push_back(image_info);
1300
1301 if (image_info.GetModule() && m_process->GetStopID() == image_info.GetProcessStopId())
1302 loaded_module_list.AppendIfNeeded (image_info.GetModule());
1303
1304 if (s && load_kexts)
1305 s->Printf (".");
1306
1307 if (log)
1308 kext_summaries[new_kext].PutToLog (log);
1309 }
1310 }
1311 m_process->GetTarget().ModulesDidLoad (loaded_module_list);
1312 }
1313
1314 if (number_of_old_kexts_being_removed > 0)
1315 {
1316 ModuleList loaded_module_list;
1317 const uint32_t num_of_old_kexts = m_known_kexts.size();
1318 for (uint32_t old_kext = 0; old_kext < num_of_old_kexts; old_kext++)
1319 {
1320 ModuleList unloaded_module_list;
1321 if (to_be_removed[old_kext])
1322 {
1323 KextImageInfo &image_info = m_known_kexts[old_kext];
1324 // You can't unload the kernel.
1325 if (!image_info.IsKernel())
1326 {
1327 if (image_info.GetModule())
1328 {
1329 unloaded_module_list.AppendIfNeeded (image_info.GetModule());
1330 }
1331 if (s)
1332 s->Printf (".");
1333 image_info.Clear();
1334 // should pull it out of the KextImageInfos vector but that would mutate the list and invalidate
1335 // the to_be_removed bool vector; leaving it in place once Cleared() is relatively harmless.
1336 }
1337 }
1338 m_process->GetTarget().ModulesDidUnload (unloaded_module_list);
1339 }
1340 }
1341
1342 if (s && load_kexts)
1343 {
1344 s->Printf (" done.\n");
1345 s->Flush ();
1346 }
1347
1348 return true;
1349 }
1350
1351 uint32_t
ReadKextSummaries(const Address & kext_summary_addr,uint32_t image_infos_count,KextImageInfo::collection & image_infos)1352 DynamicLoaderDarwinKernel::ReadKextSummaries (const Address &kext_summary_addr,
1353 uint32_t image_infos_count,
1354 KextImageInfo::collection &image_infos)
1355 {
1356 const ByteOrder endian = m_kernel.GetByteOrder();
1357 const uint32_t addr_size = m_kernel.GetAddressByteSize();
1358
1359 image_infos.resize(image_infos_count);
1360 const size_t count = image_infos.size() * m_kext_summary_header.entry_size;
1361 DataBufferHeap data(count, 0);
1362 Error error;
1363
1364 const bool prefer_file_cache = false;
1365 const size_t bytes_read = m_process->GetTarget().ReadMemory (kext_summary_addr,
1366 prefer_file_cache,
1367 data.GetBytes(),
1368 data.GetByteSize(),
1369 error);
1370 if (bytes_read == count)
1371 {
1372
1373 DataExtractor extractor (data.GetBytes(), data.GetByteSize(), endian, addr_size);
1374 uint32_t i=0;
1375 for (uint32_t kext_summary_offset = 0;
1376 i < image_infos.size() && extractor.ValidOffsetForDataOfSize(kext_summary_offset, m_kext_summary_header.entry_size);
1377 ++i, kext_summary_offset += m_kext_summary_header.entry_size)
1378 {
1379 lldb::offset_t offset = kext_summary_offset;
1380 const void *name_data = extractor.GetData(&offset, KERNEL_MODULE_MAX_NAME);
1381 if (name_data == NULL)
1382 break;
1383 image_infos[i].SetName ((const char *) name_data);
1384 UUID uuid (extractor.GetData (&offset, 16), 16);
1385 image_infos[i].SetUUID (uuid);
1386 image_infos[i].SetLoadAddress (extractor.GetU64(&offset));
1387 image_infos[i].SetSize (extractor.GetU64(&offset));
1388 }
1389 if (i < image_infos.size())
1390 image_infos.resize(i);
1391 }
1392 else
1393 {
1394 image_infos.clear();
1395 }
1396 return image_infos.size();
1397 }
1398
1399 bool
ReadAllKextSummaries()1400 DynamicLoaderDarwinKernel::ReadAllKextSummaries ()
1401 {
1402 Mutex::Locker locker(m_mutex);
1403
1404 if (ReadKextSummaryHeader ())
1405 {
1406 if (m_kext_summary_header.entry_count > 0 && m_kext_summary_header_addr.IsValid())
1407 {
1408 Address summary_addr (m_kext_summary_header_addr);
1409 summary_addr.Slide(m_kext_summary_header.GetSize());
1410 if (!ParseKextSummaries (summary_addr, m_kext_summary_header.entry_count))
1411 {
1412 m_known_kexts.clear();
1413 }
1414 return true;
1415 }
1416 }
1417 return false;
1418 }
1419
1420 //----------------------------------------------------------------------
1421 // Dump an image info structure to the file handle provided.
1422 //----------------------------------------------------------------------
1423 void
PutToLog(Log * log) const1424 DynamicLoaderDarwinKernel::KextImageInfo::PutToLog (Log *log) const
1425 {
1426 if (log == NULL)
1427 return;
1428 const uint8_t *u = (uint8_t *) m_uuid.GetBytes();
1429
1430 if (m_load_address == LLDB_INVALID_ADDRESS)
1431 {
1432 if (u)
1433 {
1434 log->Printf("\tuuid=%2.2X%2.2X%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X%2.2X%2.2X%2.2X%2.2X name=\"%s\" (UNLOADED)",
1435 u[ 0], u[ 1], u[ 2], u[ 3],
1436 u[ 4], u[ 5], u[ 6], u[ 7],
1437 u[ 8], u[ 9], u[10], u[11],
1438 u[12], u[13], u[14], u[15],
1439 m_name.c_str());
1440 }
1441 else
1442 log->Printf("\tname=\"%s\" (UNLOADED)", m_name.c_str());
1443 }
1444 else
1445 {
1446 if (u)
1447 {
1448 log->Printf("\taddr=0x%16.16" PRIx64 " size=0x%16.16" PRIx64 " uuid=%2.2X%2.2X%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X%2.2X%2.2X%2.2X%2.2X name=\"%s\"",
1449 m_load_address, m_size,
1450 u[ 0], u[ 1], u[ 2], u[ 3], u[ 4], u[ 5], u[ 6], u[ 7],
1451 u[ 8], u[ 9], u[10], u[11], u[12], u[13], u[14], u[15],
1452 m_name.c_str());
1453 }
1454 else
1455 {
1456 log->Printf("\t[0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ") name=\"%s\"",
1457 m_load_address, m_load_address+m_size, m_name.c_str());
1458 }
1459 }
1460 }
1461
1462 //----------------------------------------------------------------------
1463 // Dump the _dyld_all_image_infos members and all current image infos
1464 // that we have parsed to the file handle provided.
1465 //----------------------------------------------------------------------
1466 void
PutToLog(Log * log) const1467 DynamicLoaderDarwinKernel::PutToLog(Log *log) const
1468 {
1469 if (log == NULL)
1470 return;
1471
1472 Mutex::Locker locker(m_mutex);
1473 log->Printf("gLoadedKextSummaries = 0x%16.16" PRIx64 " { version=%u, entry_size=%u, entry_count=%u }",
1474 m_kext_summary_header_addr.GetFileAddress(),
1475 m_kext_summary_header.version,
1476 m_kext_summary_header.entry_size,
1477 m_kext_summary_header.entry_count);
1478
1479 size_t i;
1480 const size_t count = m_known_kexts.size();
1481 if (count > 0)
1482 {
1483 log->PutCString("Loaded:");
1484 for (i = 0; i<count; i++)
1485 m_known_kexts[i].PutToLog(log);
1486 }
1487 }
1488
1489 void
PrivateInitialize(Process * process)1490 DynamicLoaderDarwinKernel::PrivateInitialize(Process *process)
1491 {
1492 DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState()));
1493 Clear(true);
1494 m_process = process;
1495 }
1496
1497 void
SetNotificationBreakpointIfNeeded()1498 DynamicLoaderDarwinKernel::SetNotificationBreakpointIfNeeded ()
1499 {
1500 if (m_break_id == LLDB_INVALID_BREAK_ID && m_kernel.GetModule())
1501 {
1502 DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState()));
1503
1504
1505 const bool internal_bp = true;
1506 const LazyBool skip_prologue = eLazyBoolNo;
1507 FileSpecList module_spec_list;
1508 module_spec_list.Append (m_kernel.GetModule()->GetFileSpec());
1509 Breakpoint *bp = m_process->GetTarget().CreateBreakpoint (&module_spec_list,
1510 NULL,
1511 "OSKextLoadedKextSummariesUpdated",
1512 eFunctionNameTypeFull,
1513 skip_prologue,
1514 internal_bp).get();
1515
1516 bp->SetCallback (DynamicLoaderDarwinKernel::BreakpointHitCallback, this, true);
1517 m_break_id = bp->GetID();
1518 }
1519 }
1520
1521 //----------------------------------------------------------------------
1522 // Member function that gets called when the process state changes.
1523 //----------------------------------------------------------------------
1524 void
PrivateProcessStateChanged(Process * process,StateType state)1525 DynamicLoaderDarwinKernel::PrivateProcessStateChanged (Process *process, StateType state)
1526 {
1527 DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s(%s)\n", __FUNCTION__, StateAsCString(state));
1528 switch (state)
1529 {
1530 case eStateConnected:
1531 case eStateAttaching:
1532 case eStateLaunching:
1533 case eStateInvalid:
1534 case eStateUnloaded:
1535 case eStateExited:
1536 case eStateDetached:
1537 Clear(false);
1538 break;
1539
1540 case eStateStopped:
1541 UpdateIfNeeded();
1542 break;
1543
1544 case eStateRunning:
1545 case eStateStepping:
1546 case eStateCrashed:
1547 case eStateSuspended:
1548 break;
1549 }
1550 }
1551
1552 ThreadPlanSP
GetStepThroughTrampolinePlan(Thread & thread,bool stop_others)1553 DynamicLoaderDarwinKernel::GetStepThroughTrampolinePlan (Thread &thread, bool stop_others)
1554 {
1555 ThreadPlanSP thread_plan_sp;
1556 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1557 if (log)
1558 log->Printf ("Could not find symbol for step through.");
1559 return thread_plan_sp;
1560 }
1561
1562 Error
CanLoadImage()1563 DynamicLoaderDarwinKernel::CanLoadImage ()
1564 {
1565 Error error;
1566 error.SetErrorString("always unsafe to load or unload shared libraries in the darwin kernel");
1567 return error;
1568 }
1569
1570 void
Initialize()1571 DynamicLoaderDarwinKernel::Initialize()
1572 {
1573 PluginManager::RegisterPlugin (GetPluginNameStatic(),
1574 GetPluginDescriptionStatic(),
1575 CreateInstance,
1576 DebuggerInitialize);
1577 }
1578
1579 void
Terminate()1580 DynamicLoaderDarwinKernel::Terminate()
1581 {
1582 PluginManager::UnregisterPlugin (CreateInstance);
1583 }
1584
1585 void
DebuggerInitialize(lldb_private::Debugger & debugger)1586 DynamicLoaderDarwinKernel::DebuggerInitialize (lldb_private::Debugger &debugger)
1587 {
1588 if (!PluginManager::GetSettingForDynamicLoaderPlugin (debugger, DynamicLoaderDarwinKernelProperties::GetSettingName()))
1589 {
1590 const bool is_global_setting = true;
1591 PluginManager::CreateSettingForDynamicLoaderPlugin (debugger,
1592 GetGlobalProperties()->GetValueProperties(),
1593 ConstString ("Properties for the DynamicLoaderDarwinKernel plug-in."),
1594 is_global_setting);
1595 }
1596 }
1597
1598 lldb_private::ConstString
GetPluginNameStatic()1599 DynamicLoaderDarwinKernel::GetPluginNameStatic()
1600 {
1601 static ConstString g_name("darwin-kernel");
1602 return g_name;
1603 }
1604
1605 const char *
GetPluginDescriptionStatic()1606 DynamicLoaderDarwinKernel::GetPluginDescriptionStatic()
1607 {
1608 return "Dynamic loader plug-in that watches for shared library loads/unloads in the MacOSX kernel.";
1609 }
1610
1611
1612 //------------------------------------------------------------------
1613 // PluginInterface protocol
1614 //------------------------------------------------------------------
1615 lldb_private::ConstString
GetPluginName()1616 DynamicLoaderDarwinKernel::GetPluginName()
1617 {
1618 return GetPluginNameStatic();
1619 }
1620
1621 uint32_t
GetPluginVersion()1622 DynamicLoaderDarwinKernel::GetPluginVersion()
1623 {
1624 return 1;
1625 }
1626
1627 lldb::ByteOrder
GetByteOrderFromMagic(uint32_t magic)1628 DynamicLoaderDarwinKernel::GetByteOrderFromMagic (uint32_t magic)
1629 {
1630 switch (magic)
1631 {
1632 case llvm::MachO::HeaderMagic32:
1633 case llvm::MachO::HeaderMagic64:
1634 return lldb::endian::InlHostByteOrder();
1635
1636 case llvm::MachO::HeaderMagic32Swapped:
1637 case llvm::MachO::HeaderMagic64Swapped:
1638 if (lldb::endian::InlHostByteOrder() == lldb::eByteOrderBig)
1639 return lldb::eByteOrderLittle;
1640 else
1641 return lldb::eByteOrderBig;
1642
1643 default:
1644 break;
1645 }
1646 return lldb::eByteOrderInvalid;
1647 }
1648
1649