blob: c9d338370eadce265cddad5be321583c214dde80 [file] [log] [blame]
Greg Clayton944b8282011-08-22 22:30:57 +00001//===-- DynamicLoaderDarwinKernel.cpp -----------------------------*- C++ -*-===//
Greg Clayton7b242382011-07-08 00:48:09 +00002//
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
Daniel Malea93a64302012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Greg Clayton7b242382011-07-08 00:48:09 +000012#include "lldb/Breakpoint/StoppointCallbackContext.h"
13#include "lldb/Core/DataBuffer.h"
14#include "lldb/Core/DataBufferHeap.h"
Greg Clayton07e66e32011-07-20 03:41:06 +000015#include "lldb/Core/Debugger.h"
Greg Clayton7b242382011-07-08 00:48:09 +000016#include "lldb/Core/Log.h"
17#include "lldb/Core/Module.h"
Greg Clayton1f746072012-08-29 21:13:06 +000018#include "lldb/Core/ModuleSpec.h"
Greg Clayton7b242382011-07-08 00:48:09 +000019#include "lldb/Core/PluginManager.h"
Greg Clayton1f746072012-08-29 21:13:06 +000020#include "lldb/Core/Section.h"
Greg Clayton7b242382011-07-08 00:48:09 +000021#include "lldb/Core/State.h"
Jason Molenda68b36072012-10-02 03:49:41 +000022#include "lldb/Host/Symbols.h"
Greg Clayton7b242382011-07-08 00:48:09 +000023#include "lldb/Symbol/ObjectFile.h"
Greg Clayton7b242382011-07-08 00:48:09 +000024#include "lldb/Target/RegisterContext.h"
Jason Molenda68b36072012-10-02 03:49:41 +000025#include "lldb/Target/StackFrame.h"
Greg Clayton7b242382011-07-08 00:48:09 +000026#include "lldb/Target/Target.h"
27#include "lldb/Target/Thread.h"
28#include "lldb/Target/ThreadPlanRunToAddress.h"
Jason Molenda68b36072012-10-02 03:49:41 +000029
Greg Clayton7b242382011-07-08 00:48:09 +000030
Greg Clayton944b8282011-08-22 22:30:57 +000031#include "DynamicLoaderDarwinKernel.h"
Greg Clayton7b242382011-07-08 00:48:09 +000032
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
41using namespace lldb;
42using namespace lldb_private;
43
Jason Molenda6ba6d3d2013-01-30 04:39:32 +000044// 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
48enum 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 64 locations total
53 eKASLRScanExhaustiveScan // Scan through the entire possible kernel address range looking for a kernel
54};
55
56OptionEnumValueElement
57g_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
Greg Claytone8cd0c92012-10-19 18:02:49 +000066static PropertyDefinition
67g_properties[] =
68{
Greg Clayton66763ee2012-10-19 20:53:18 +000069 { "load-kexts" , OptionValue::eTypeBoolean, true, true, NULL, NULL, "Automatically loads kext images when attaching to a kernel." },
Jason Molenda6ba6d3d2013-01-30 04:39:32 +000070 { "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." },
Greg Clayton66763ee2012-10-19 20:53:18 +000071 { NULL , OptionValue::eTypeInvalid, false, 0 , NULL, NULL, NULL }
Greg Claytone8cd0c92012-10-19 18:02:49 +000072};
73
74enum {
Jason Molenda6ba6d3d2013-01-30 04:39:32 +000075 ePropertyLoadKexts,
76 ePropertyScanType
Greg Claytone8cd0c92012-10-19 18:02:49 +000077};
78
79class DynamicLoaderDarwinKernelProperties : public Properties
80{
81public:
82
83 static ConstString &
84 GetSettingName ()
85 {
Greg Clayton468ea4e2012-10-19 18:14:47 +000086 static ConstString g_setting_name("darwin-kernel");
Greg Claytone8cd0c92012-10-19 18:02:49 +000087 return g_setting_name;
88 }
89
90 DynamicLoaderDarwinKernelProperties() :
91 Properties ()
92 {
93 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
94 m_collection_sp->Initialize(g_properties);
95 }
96
97 virtual
98 ~DynamicLoaderDarwinKernelProperties()
99 {
100 }
Jason Molenda6ba6d3d2013-01-30 04:39:32 +0000101
Greg Claytone8cd0c92012-10-19 18:02:49 +0000102 bool
Greg Clayton66763ee2012-10-19 20:53:18 +0000103 GetLoadKexts() const
Greg Claytone8cd0c92012-10-19 18:02:49 +0000104 {
Greg Clayton66763ee2012-10-19 20:53:18 +0000105 const uint32_t idx = ePropertyLoadKexts;
Greg Claytone8cd0c92012-10-19 18:02:49 +0000106 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
107 }
Jason Molenda6ba6d3d2013-01-30 04:39:32 +0000108
109 KASLRScanType
110 GetScanType() const
111 {
112 const uint32_t idx = ePropertyScanType;
113 return (KASLRScanType) m_collection_sp->SetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
114 }
115
116
Greg Claytone8cd0c92012-10-19 18:02:49 +0000117};
118
119typedef STD_SHARED_PTR(DynamicLoaderDarwinKernelProperties) DynamicLoaderDarwinKernelPropertiesSP;
120
121static const DynamicLoaderDarwinKernelPropertiesSP &
122GetGlobalProperties()
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
Greg Clayton7b242382011-07-08 00:48:09 +0000130//----------------------------------------------------------------------
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//----------------------------------------------------------------------
135DynamicLoader *
Greg Clayton944b8282011-08-22 22:30:57 +0000136DynamicLoaderDarwinKernel::CreateInstance (Process* process, bool force)
Greg Clayton7b242382011-07-08 00:48:09 +0000137{
Jason Molenda6ba6d3d2013-01-30 04:39:32 +0000138 if (!force)
Greg Clayton7b242382011-07-08 00:48:09 +0000139 {
Jason Molenda6ba6d3d2013-01-30 04:39:32 +0000140 // If the user provided an executable binary and it is not a kernel,
141 // this plugin should not create an instance.
Greg Claytonaa149cb2011-08-11 02:48:45 +0000142 Module* exe_module = process->GetTarget().GetExecutableModulePointer();
Greg Claytondf0b7d52011-07-08 04:11:42 +0000143 if (exe_module)
144 {
145 ObjectFile *object_file = exe_module->GetObjectFile();
146 if (object_file)
147 {
Jason Molenda6ba6d3d2013-01-30 04:39:32 +0000148 if (object_file->GetStrata() != ObjectFile::eStrataKernel)
149 {
150 return NULL;
151 }
Greg Claytondf0b7d52011-07-08 04:11:42 +0000152 }
153 }
Jason Molenda6ba6d3d2013-01-30 04:39:32 +0000154
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())
Greg Claytondf0b7d52011-07-08 04:11:42 +0000159 {
Jason Molenda6ba6d3d2013-01-30 04:39:32 +0000160 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 = process->GetImageInfoAddress();
181 if (kernel_load_address == LLDB_INVALID_ADDRESS)
182 {
183 kernel_load_address = SearchForKernelAtSameLoadAddr (process);
184 if (kernel_load_address == LLDB_INVALID_ADDRESS)
185 {
186 kernel_load_address = SearchForKernelWithDebugHints (process);
187 if (kernel_load_address == LLDB_INVALID_ADDRESS)
Greg Clayton70512312012-05-08 01:45:38 +0000188 {
Jason Molenda6ba6d3d2013-01-30 04:39:32 +0000189 kernel_load_address = SearchForKernelNearPC (process);
190 if (kernel_load_address == LLDB_INVALID_ADDRESS)
191 {
192 kernel_load_address = SearchForKernelViaExhaustiveSearch (process);
193 }
Greg Clayton70512312012-05-08 01:45:38 +0000194 }
Greg Claytondf0b7d52011-07-08 04:11:42 +0000195 }
Greg Clayton7b242382011-07-08 00:48:09 +0000196 }
Jason Molenda6ba6d3d2013-01-30 04:39:32 +0000197
198 if (kernel_load_address != LLDB_INVALID_ADDRESS)
Sean Callanan90539452011-09-20 23:01:51 +0000199 {
200 process->SetCanJIT(false);
Jason Molenda6ba6d3d2013-01-30 04:39:32 +0000201 return new DynamicLoaderDarwinKernel (process, kernel_load_address);
Sean Callanan90539452011-09-20 23:01:51 +0000202 }
Greg Clayton7b242382011-07-08 00:48:09 +0000203 return NULL;
204}
205
206//----------------------------------------------------------------------
Jason Molenda6ba6d3d2013-01-30 04:39:32 +0000207// Check if the kernel binary is loaded in memory without a slide.
208// First verify that the ExecutableModule is a kernel before we proceed.
209// Returns the address of the kernel if one was found, else LLDB_INVALID_ADDRESS.
210//----------------------------------------------------------------------
211lldb::addr_t
212DynamicLoaderDarwinKernel::SearchForKernelAtSameLoadAddr (Process *process)
213{
214 Module *exe_module = process->GetTarget().GetExecutableModulePointer();
215 if (exe_module == NULL)
216 return LLDB_INVALID_ADDRESS;
217
218 ObjectFile *exe_objfile = exe_module->GetObjectFile();
219 if (exe_objfile == NULL)
220 return LLDB_INVALID_ADDRESS;
221
222 if (exe_objfile->GetType() != ObjectFile::eTypeExecutable || exe_objfile->GetStrata() != ObjectFile::eStrataKernel)
223 return LLDB_INVALID_ADDRESS;
224
225 if (!exe_objfile->GetHeaderAddress().IsValid())
226 return LLDB_INVALID_ADDRESS;
227
228 if (CheckForKernelImageAtAddress (exe_objfile->GetHeaderAddress().GetFileAddress(), process) == exe_module->GetUUID())
229 return exe_objfile->GetHeaderAddress().GetFileAddress();
230
231 return LLDB_INVALID_ADDRESS;
232}
233
234//----------------------------------------------------------------------
235// If the debug flag is included in the boot-args nvram setting, the kernel's load address
236// will be noted in the lowglo page at a fixed address
237// Returns the address of the kernel if one was found, else LLDB_INVALID_ADDRESS.
238//----------------------------------------------------------------------
239lldb::addr_t
240DynamicLoaderDarwinKernel::SearchForKernelWithDebugHints (Process *process)
241{
242#if 0
243 if (GetGlobalProperties()->GetScanType() == eKASLRScanNone)
244 return LLDB_INVALID_ADDRESS;
245#endif
246
247 Error read_err;
248 addr_t addr = LLDB_INVALID_ADDRESS;
249 if (process->GetTarget().GetArchitecture().GetAddressByteSize() == 8)
250 {
251 addr = process->ReadUnsignedIntegerFromMemory (0xffffff8000002010ULL, 8, LLDB_INVALID_ADDRESS, read_err);
252 }
253 else
254 {
255 addr = process->ReadUnsignedIntegerFromMemory (0xffff0110, 4, LLDB_INVALID_ADDRESS, read_err);
256 }
257
258 if (addr == 0)
259 addr = LLDB_INVALID_ADDRESS;
260
261 if (addr != LLDB_INVALID_ADDRESS)
262 {
263 if (CheckForKernelImageAtAddress (addr, process).IsValid())
264 return addr;
265 }
266
267 return LLDB_INVALID_ADDRESS;
268}
269
270//----------------------------------------------------------------------
271// If the kernel is currently executing when lldb attaches, and we don't have
272// a better way of finding the kernel's load address, try searching backwards
273// from the current pc value looking for the kernel's Mach header in memory.
274// Returns the address of the kernel if one was found, else LLDB_INVALID_ADDRESS.
275//----------------------------------------------------------------------
276lldb::addr_t
277DynamicLoaderDarwinKernel::SearchForKernelNearPC (Process *process)
278{
279#if 0
280 if (GetGlobalProperties()->GetScanType() == eKASLRScanNone
281 || GetGlobalProperties()->GetScanType() == eKASLRScanLowgloAddresses)
282 {
283 return LLDB_INVALID_ADDRESS;
284 }
285#endif
286
287 ThreadSP thread = process->GetThreadList().GetSelectedThread ();
288 if (thread.get() == NULL)
289 return LLDB_INVALID_ADDRESS;
290 addr_t pc = thread->GetRegisterContext ()->GetPC(LLDB_INVALID_ADDRESS);
291
292 if (pc == LLDB_INVALID_ADDRESS)
293 return LLDB_INVALID_ADDRESS;
294
295 addr_t kernel_range_low, kernel_range_high;
296 if (process->GetTarget().GetArchitecture().GetAddressByteSize() == 8)
297 {
298 kernel_range_low = 1ULL << 63;
299 kernel_range_high = UINT64_MAX;
300 }
301 else
302 {
303 kernel_range_low = 1ULL << 31;
304 kernel_range_high = UINT32_MAX;
305 }
306
307 // Outside the normal kernel address range, this is probably userland code running right now
308 if (pc < kernel_range_low)
309 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//----------------------------------------------------------------------
339lldb::addr_t
340DynamicLoaderDarwinKernel::SearchForKernelViaExhaustiveSearch (Process *process)
341{
342#if 0
343 if (GetGlobalProperties()->GetScanType() != eKASLRScanExhaustiveScan)
344 {
345 return LLDB_INVALID_ADDRESS;
346 }
347#endif
348
349 addr_t kernel_range_low, kernel_range_high;
350 if (process->GetTarget().GetArchitecture().GetAddressByteSize() == 8)
351 {
352 kernel_range_low = 1ULL << 63;
353 kernel_range_high = UINT64_MAX;
354 }
355 else
356 {
357 kernel_range_low = 1ULL << 31;
358 kernel_range_high = UINT32_MAX;
359 }
360
361 // Stepping through memory at one-megabyte resolution looking for a kernel
362 // rarely works (fast enough) with a 64-bit address space -- for now, let's
363 // not even bother. We may be attaching to something which *isn't* a kernel
364 // and we don't want to spin for minutes on-end looking for a kernel.
365 if (process->GetTarget().GetArchitecture().GetAddressByteSize() == 8)
366 return LLDB_INVALID_ADDRESS;
367
368 addr_t addr = kernel_range_low;
369
370 while (addr >= kernel_range_low && addr < kernel_range_high)
371 {
372 if (CheckForKernelImageAtAddress (addr, process).IsValid())
373 return addr;
374 if (CheckForKernelImageAtAddress (addr + 0x1000, process).IsValid())
375 return addr + 0x1000;
376 if (CheckForKernelImageAtAddress (addr + 0x2000, process).IsValid())
377 return addr + 0x2000;
378 addr += 0x100000;
379 }
380 return LLDB_INVALID_ADDRESS;
381}
382
383//----------------------------------------------------------------------
384// Given an address in memory, look to see if there is a kernel image at that
385// address.
386// Returns a UUID; if a kernel was not found at that address, UUID.IsValid() will be false.
387//----------------------------------------------------------------------
388lldb_private::UUID
389DynamicLoaderDarwinKernel::CheckForKernelImageAtAddress (lldb::addr_t addr, Process *process)
390{
391 if (addr == LLDB_INVALID_ADDRESS)
392 return UUID();
393
394 // First try a quick test -- read the first 4 bytes and see if there is a valid Mach-O magic field there
395 // (the first field of the mach_header/mach_header_64 struct).
396
397 Error read_error;
398 uint64_t result = process->ReadUnsignedIntegerFromMemory (addr, 4, LLDB_INVALID_ADDRESS, read_error);
399 if (result != llvm::MachO::HeaderMagic64
400 && result != llvm::MachO::HeaderMagic32
401 && result != llvm::MachO::HeaderMagic32Swapped
402 && result != llvm::MachO::HeaderMagic64Swapped)
403 {
404 return UUID();
405 }
406
407 // Read the mach header and see whether it looks like a kernel
408 llvm::MachO::mach_header header;
409 if (process->DoReadMemory (addr, &header, sizeof(header), read_error) != sizeof(header))
410 return UUID();
411
412 if (header.magic == llvm::MachO::HeaderMagic32Swapped ||
413 header.magic == llvm::MachO::HeaderMagic64Swapped)
414 {
415 header.magic = llvm::ByteSwap_32(header.magic);
416 header.cputype = llvm::ByteSwap_32(header.cputype);
417 header.cpusubtype = llvm::ByteSwap_32(header.cpusubtype);
418 header.filetype = llvm::ByteSwap_32(header.filetype);
419 header.ncmds = llvm::ByteSwap_32(header.ncmds);
420 header.sizeofcmds = llvm::ByteSwap_32(header.sizeofcmds);
421 header.flags = llvm::ByteSwap_32(header.flags);
422 }
423
424 // A kernel is an executable which does not have the dynamic link object flag set.
425 if (header.filetype == llvm::MachO::HeaderFileTypeExecutable
426 && (header.flags & llvm::MachO::HeaderFlagBitIsDynamicLinkObject) == 0)
427 {
428 // Create a full module to get the UUID
429 ModuleSP memory_module_sp = process->ReadModuleFromMemory (FileSpec ("temp_mach_kernel", false), addr, false, false);
430 if (!memory_module_sp.get())
431 return UUID();
432
433 ObjectFile *exe_objfile = memory_module_sp->GetObjectFile();
434 if (exe_objfile == NULL)
435 return UUID();
436
437 if (exe_objfile->GetType() == ObjectFile::eTypeExecutable && exe_objfile->GetStrata() == ObjectFile::eStrataKernel)
438 {
439 return memory_module_sp->GetUUID();
440 }
441 }
442
443 return UUID();
444}
445
446//----------------------------------------------------------------------
Greg Clayton7b242382011-07-08 00:48:09 +0000447// Constructor
448//----------------------------------------------------------------------
Jason Molenda6ba6d3d2013-01-30 04:39:32 +0000449DynamicLoaderDarwinKernel::DynamicLoaderDarwinKernel (Process* process, lldb::addr_t kernel_addr) :
Greg Clayton7b242382011-07-08 00:48:09 +0000450 DynamicLoader(process),
Jason Molenda6ba6d3d2013-01-30 04:39:32 +0000451 m_kernel_load_address (kernel_addr),
Greg Clayton7b242382011-07-08 00:48:09 +0000452 m_kernel(),
Greg Claytond16e1e52011-07-12 17:06:17 +0000453 m_kext_summary_header_ptr_addr (),
Greg Clayton0d9fc762011-07-08 03:21:57 +0000454 m_kext_summary_header_addr (),
Greg Clayton7b242382011-07-08 00:48:09 +0000455 m_kext_summary_header (),
Greg Clayton7b242382011-07-08 00:48:09 +0000456 m_kext_summaries(),
Daniel Dunbara08823f2011-10-31 22:50:49 +0000457 m_mutex(Mutex::eMutexTypeRecursive),
458 m_break_id (LLDB_INVALID_BREAK_ID)
Greg Clayton7b242382011-07-08 00:48:09 +0000459{
460}
461
462//----------------------------------------------------------------------
463// Destructor
464//----------------------------------------------------------------------
Greg Clayton944b8282011-08-22 22:30:57 +0000465DynamicLoaderDarwinKernel::~DynamicLoaderDarwinKernel()
Greg Clayton7b242382011-07-08 00:48:09 +0000466{
467 Clear(true);
468}
469
Greg Clayton374972e2011-07-09 17:15:55 +0000470void
Greg Clayton944b8282011-08-22 22:30:57 +0000471DynamicLoaderDarwinKernel::UpdateIfNeeded()
Greg Clayton374972e2011-07-09 17:15:55 +0000472{
473 LoadKernelModuleIfNeeded();
474 SetNotificationBreakpointIfNeeded ();
475}
Greg Clayton7b242382011-07-08 00:48:09 +0000476//------------------------------------------------------------------
477/// Called after attaching a process.
478///
479/// Allow DynamicLoader plug-ins to execute some code after
480/// attaching to a process.
481//------------------------------------------------------------------
482void
Greg Clayton944b8282011-08-22 22:30:57 +0000483DynamicLoaderDarwinKernel::DidAttach ()
Greg Clayton7b242382011-07-08 00:48:09 +0000484{
485 PrivateInitialize(m_process);
Greg Clayton374972e2011-07-09 17:15:55 +0000486 UpdateIfNeeded();
Greg Clayton7b242382011-07-08 00:48:09 +0000487}
488
489//------------------------------------------------------------------
490/// Called after attaching a process.
491///
492/// Allow DynamicLoader plug-ins to execute some code after
493/// attaching to a process.
494//------------------------------------------------------------------
495void
Greg Clayton944b8282011-08-22 22:30:57 +0000496DynamicLoaderDarwinKernel::DidLaunch ()
Greg Clayton7b242382011-07-08 00:48:09 +0000497{
498 PrivateInitialize(m_process);
Greg Clayton374972e2011-07-09 17:15:55 +0000499 UpdateIfNeeded();
Greg Clayton7b242382011-07-08 00:48:09 +0000500}
501
502
503//----------------------------------------------------------------------
504// Clear out the state of this class.
505//----------------------------------------------------------------------
506void
Greg Clayton944b8282011-08-22 22:30:57 +0000507DynamicLoaderDarwinKernel::Clear (bool clear_process)
Greg Clayton7b242382011-07-08 00:48:09 +0000508{
509 Mutex::Locker locker(m_mutex);
510
511 if (m_process->IsAlive() && LLDB_BREAK_ID_IS_VALID(m_break_id))
512 m_process->ClearBreakpointSiteByID(m_break_id);
513
514 if (clear_process)
515 m_process = NULL;
516 m_kernel.Clear(false);
Greg Claytond16e1e52011-07-12 17:06:17 +0000517 m_kext_summary_header_ptr_addr.Clear();
Greg Clayton0d9fc762011-07-08 03:21:57 +0000518 m_kext_summary_header_addr.Clear();
Greg Clayton7b242382011-07-08 00:48:09 +0000519 m_kext_summaries.clear();
Greg Clayton7b242382011-07-08 00:48:09 +0000520 m_break_id = LLDB_INVALID_BREAK_ID;
521}
522
Greg Clayton7b242382011-07-08 00:48:09 +0000523
Greg Claytonc859e2d2012-02-13 23:10:39 +0000524bool
Greg Clayton2af282a2012-03-21 04:25:00 +0000525DynamicLoaderDarwinKernel::OSKextLoadedKextSummary::LoadImageAtFileAddress (Process *process)
526{
527 if (IsLoaded())
528 return true;
529
530 if (module_sp)
531 {
532 bool changed = false;
533 if (module_sp->SetLoadAddress (process->GetTarget(), 0, changed))
534 load_process_stop_id = process->GetStopID();
535 }
536 return false;
537}
538
539bool
Greg Claytonc859e2d2012-02-13 23:10:39 +0000540DynamicLoaderDarwinKernel::OSKextLoadedKextSummary::LoadImageUsingMemoryModule (Process *process)
541{
542 if (IsLoaded())
543 return true;
544
545 bool uuid_is_valid = uuid.IsValid();
Jason Molenda68b36072012-10-02 03:49:41 +0000546 bool memory_module_is_kernel = false;
Greg Claytonc859e2d2012-02-13 23:10:39 +0000547
548 Target &target = process->GetTarget();
549 ModuleSP memory_module_sp;
Jason Molenda87a04b22012-10-19 03:40:45 +0000550
551 // If this is a kext and the user asked us to ignore kexts, don't try to load it.
Greg Clayton66763ee2012-10-19 20:53:18 +0000552 if (kernel_image == false && GetGlobalProperties()->GetLoadKexts() == false)
Jason Molenda87a04b22012-10-19 03:40:45 +0000553 {
554 return false;
555 }
556
557 // Use the memory module as the module if we have one
Greg Claytonc859e2d2012-02-13 23:10:39 +0000558 if (address != LLDB_INVALID_ADDRESS)
559 {
560 FileSpec file_spec;
561 if (module_sp)
562 file_spec = module_sp->GetFileSpec();
563 else
564 file_spec.SetFile (name, false);
565
566 memory_module_sp = process->ReadModuleFromMemory (file_spec, address, false, false);
567 if (memory_module_sp && !uuid_is_valid)
568 {
569 uuid = memory_module_sp->GetUUID();
570 uuid_is_valid = uuid.IsValid();
571 }
Jason Molendac56bd082012-11-08 00:19:28 +0000572 if (memory_module_sp
573 && memory_module_sp->GetObjectFile()
Jason Molenda68b36072012-10-02 03:49:41 +0000574 && memory_module_sp->GetObjectFile()->GetType() == ObjectFile::eTypeExecutable
575 && memory_module_sp->GetObjectFile()->GetStrata() == ObjectFile::eStrataKernel)
576 {
577 memory_module_is_kernel = true;
Jason Molenda53667f52012-10-06 02:02:26 +0000578 if (memory_module_sp->GetArchitecture().IsValid())
579 {
580 target.SetArchitecture(memory_module_sp->GetArchitecture());
581 }
Jason Molenda68b36072012-10-02 03:49:41 +0000582 }
Greg Claytonc859e2d2012-02-13 23:10:39 +0000583 }
584
585 if (!module_sp)
586 {
Greg Claytonc859e2d2012-02-13 23:10:39 +0000587 if (uuid_is_valid)
588 {
Enrico Granata17598482012-11-08 02:22:02 +0000589 const ModuleList &target_images = target.GetImages();
Greg Claytonc859e2d2012-02-13 23:10:39 +0000590 module_sp = target_images.FindModule(uuid);
Jason Molenda53667f52012-10-06 02:02:26 +0000591
Greg Claytonc859e2d2012-02-13 23:10:39 +0000592 if (!module_sp)
Greg Claytonb9a01b32012-02-26 05:51:37 +0000593 {
Greg Clayton2af282a2012-03-21 04:25:00 +0000594 ModuleSpec module_spec;
Greg Claytonb9a01b32012-02-26 05:51:37 +0000595 module_spec.GetUUID() = uuid;
Jason Molenda53667f52012-10-06 02:02:26 +0000596 module_spec.GetArchitecture() = target.GetArchitecture();
Jason Molendabb860bd2012-10-09 01:17:11 +0000597
598 // For the kernel, we really do need an on-disk file copy of the
599 // binary.
600 bool force_symbols_search = false;
601 if (memory_module_is_kernel)
602 {
603 force_symbols_search = true;
604 }
605
606 if (Symbols::DownloadObjectAndSymbolFile (module_spec, force_symbols_search))
607 {
608 if (module_spec.GetFileSpec().Exists())
609 {
610 module_sp.reset(new Module (module_spec.GetFileSpec(), target.GetArchitecture()));
611 if (module_sp.get() && module_sp->MatchesModuleSpec (module_spec))
612 {
613 ModuleList loaded_module_list;
614 loaded_module_list.Append (module_sp);
615 target.ModulesDidLoad (loaded_module_list);
616 }
617 }
618 }
619
620 // Ask the Target to find this file on the local system, if possible.
621 // This will search in the list of currently-loaded files, look in the
622 // standard search paths on the system, and on a Mac it will try calling
623 // the DebugSymbols framework with the UUID to find the binary via its
624 // search methods.
625 if (!module_sp)
626 {
627 module_sp = target.GetSharedModule (module_spec);
628 }
Jason Molenda65d57a32012-12-01 06:13:29 +0000629
630 // If we managed to find a module, append it to the target's list of images
631 if (module_sp && module_sp->GetUUID() == memory_module_sp->GetUUID())
632 {
633 target.GetImages().Append(module_sp);
634 if (memory_module_is_kernel && target.GetExecutableModulePointer() != module_sp.get())
635 {
636 target.SetExecutableModule (module_sp, false);
637 }
638 }
Greg Claytonb9a01b32012-02-26 05:51:37 +0000639 }
Greg Claytonc859e2d2012-02-13 23:10:39 +0000640 }
641 }
642
643
Greg Clayton67408532012-12-11 01:20:51 +0000644 static ConstString g_section_name_LINKEDIT ("__LINKEDIT");
645
Jason Molendabb860bd2012-10-09 01:17:11 +0000646 if (memory_module_sp && module_sp)
Greg Claytonc859e2d2012-02-13 23:10:39 +0000647 {
Jason Molendabb860bd2012-10-09 01:17:11 +0000648 if (module_sp->GetUUID() == memory_module_sp->GetUUID())
Greg Claytonc859e2d2012-02-13 23:10:39 +0000649 {
Jason Molendabb860bd2012-10-09 01:17:11 +0000650 ObjectFile *ondisk_object_file = module_sp->GetObjectFile();
651 ObjectFile *memory_object_file = memory_module_sp->GetObjectFile();
Greg Clayton67408532012-12-11 01:20:51 +0000652
Jason Molendabb860bd2012-10-09 01:17:11 +0000653 if (memory_object_file && ondisk_object_file)
654 {
Greg Clayton67408532012-12-11 01:20:51 +0000655 // Kexts are classified with a type of ObjectFile::eTypeSharedLibrary and
656 // a strata of ObjectFile::eStrataKernel. Ignore __LINKEDIT for kexts
657 const bool ignore_linkedit = ondisk_object_file->GetType() == ObjectFile::eTypeSharedLibrary;
658
Jason Molendabb860bd2012-10-09 01:17:11 +0000659 SectionList *ondisk_section_list = ondisk_object_file->GetSectionList ();
660 SectionList *memory_section_list = memory_object_file->GetSectionList ();
661 if (memory_section_list && ondisk_section_list)
662 {
663 const uint32_t num_ondisk_sections = ondisk_section_list->GetSize();
664 // There may be CTF sections in the memory image so we can't
665 // always just compare the number of sections (which are actually
666 // segments in mach-o parlance)
667 uint32_t sect_idx = 0;
668
669 // Use the memory_module's addresses for each section to set the
670 // file module's load address as appropriate. We don't want to use
671 // a single slide value for the entire kext - different segments may
672 // be slid different amounts by the kext loader.
673
674 uint32_t num_sections_loaded = 0;
675 for (sect_idx=0; sect_idx<num_ondisk_sections; ++sect_idx)
676 {
677 SectionSP ondisk_section_sp(ondisk_section_list->GetSectionAtIndex(sect_idx));
678 if (ondisk_section_sp)
Greg Claytonc859e2d2012-02-13 23:10:39 +0000679 {
Greg Clayton67408532012-12-11 01:20:51 +0000680 // Don't ever load __LINKEDIT as it may or may not be actually
681 // mapped into memory and there is no current way to tell.
682 // I filed rdar://problem/12851706 to track being able to tell
683 // if the __LINKEDIT is actually mapped, but until then, we need
684 // to not load the __LINKEDIT
685 if (ignore_linkedit && ondisk_section_sp->GetName() == g_section_name_LINKEDIT)
686 continue;
687
Jason Molendabb860bd2012-10-09 01:17:11 +0000688 const Section *memory_section = memory_section_list->FindSectionByName(ondisk_section_sp->GetName()).get();
689 if (memory_section)
Greg Claytonc859e2d2012-02-13 23:10:39 +0000690 {
Jason Molendabb860bd2012-10-09 01:17:11 +0000691 target.GetSectionLoadList().SetSectionLoadAddress (ondisk_section_sp, memory_section->GetFileAddress());
692 ++num_sections_loaded;
Greg Claytonc859e2d2012-02-13 23:10:39 +0000693 }
694 }
Greg Claytonc859e2d2012-02-13 23:10:39 +0000695 }
Jason Molendabb860bd2012-10-09 01:17:11 +0000696 if (num_sections_loaded > 0)
697 load_process_stop_id = process->GetStopID();
Greg Claytonc859e2d2012-02-13 23:10:39 +0000698 else
Jason Molendabb860bd2012-10-09 01:17:11 +0000699 module_sp.reset(); // No sections were loaded
Greg Claytonc859e2d2012-02-13 23:10:39 +0000700 }
701 else
Jason Molendabb860bd2012-10-09 01:17:11 +0000702 module_sp.reset(); // One or both section lists
Greg Claytonc859e2d2012-02-13 23:10:39 +0000703 }
704 else
Jason Molendabb860bd2012-10-09 01:17:11 +0000705 module_sp.reset(); // One or both object files missing
Greg Claytonc859e2d2012-02-13 23:10:39 +0000706 }
Jason Molendabb860bd2012-10-09 01:17:11 +0000707 else
708 module_sp.reset(); // UUID mismatch
Greg Claytonc859e2d2012-02-13 23:10:39 +0000709 }
Jason Molendabb860bd2012-10-09 01:17:11 +0000710
Greg Claytonc859e2d2012-02-13 23:10:39 +0000711 bool is_loaded = IsLoaded();
712
713 if (so_address.IsValid())
714 {
715 if (is_loaded)
716 so_address.SetLoadAddress (address, &target);
717 else
718 target.GetImages().ResolveFileAddress (address, so_address);
719
720 }
Jason Molenda68b36072012-10-02 03:49:41 +0000721
722 if (is_loaded && module_sp && memory_module_is_kernel)
723 {
724 Stream *s = &target.GetDebugger().GetOutputStream();
725 if (s)
726 {
727 char uuidbuf[64];
728 s->Printf ("Kernel UUID: %s\n", module_sp->GetUUID().GetAsCString(uuidbuf, sizeof (uuidbuf)));
Daniel Malead01b2952012-11-29 21:49:15 +0000729 s->Printf ("Load Address: 0x%" PRIx64 "\n", address);
Jason Molenda743e43962012-10-02 22:23:42 +0000730 if (module_sp->GetFileSpec().GetDirectory().IsEmpty())
731 {
732 s->Printf ("Loaded kernel file %s\n", module_sp->GetFileSpec().GetFilename().AsCString());
733 }
734 else
735 {
736 s->Printf ("Loaded kernel file %s/%s\n",
737 module_sp->GetFileSpec().GetDirectory().AsCString(),
738 module_sp->GetFileSpec().GetFilename().AsCString());
739 }
Jason Molenda68b36072012-10-02 03:49:41 +0000740 s->Flush ();
741 }
742 }
Greg Claytonc859e2d2012-02-13 23:10:39 +0000743 return is_loaded;
744}
745
Greg Clayton1f746072012-08-29 21:13:06 +0000746uint32_t
747DynamicLoaderDarwinKernel::OSKextLoadedKextSummary::GetAddressByteSize ()
748{
749 if (module_sp)
750 return module_sp->GetArchitecture().GetAddressByteSize();
751 return 0;
752}
753
754lldb::ByteOrder
755DynamicLoaderDarwinKernel::OSKextLoadedKextSummary::GetByteOrder()
756{
757 if (module_sp)
758 return module_sp->GetArchitecture().GetByteOrder();
759 return lldb::endian::InlHostByteOrder();
760}
761
762lldb_private::ArchSpec
763DynamicLoaderDarwinKernel::OSKextLoadedKextSummary::GetArchitecture () const
764{
765 if (module_sp)
766 return module_sp->GetArchitecture();
767 return lldb_private::ArchSpec ();
768}
769
770
Greg Clayton7b242382011-07-08 00:48:09 +0000771//----------------------------------------------------------------------
772// Load the kernel module and initialize the "m_kernel" member. Return
773// true _only_ if the kernel is loaded the first time through (subsequent
774// calls to this function should return false after the kernel has been
775// already loaded).
776//----------------------------------------------------------------------
Greg Clayton374972e2011-07-09 17:15:55 +0000777void
Greg Clayton944b8282011-08-22 22:30:57 +0000778DynamicLoaderDarwinKernel::LoadKernelModuleIfNeeded()
Greg Clayton7b242382011-07-08 00:48:09 +0000779{
Greg Claytond16e1e52011-07-12 17:06:17 +0000780 if (!m_kext_summary_header_ptr_addr.IsValid())
Greg Clayton7b242382011-07-08 00:48:09 +0000781 {
782 m_kernel.Clear(false);
783 m_kernel.module_sp = m_process->GetTarget().GetExecutableModule();
Jason Molenda87a04b22012-10-19 03:40:45 +0000784 m_kernel.kernel_image = true;
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000785
786 ConstString kernel_name("mach_kernel");
787 if (m_kernel.module_sp.get()
788 && m_kernel.module_sp->GetObjectFile()
789 && !m_kernel.module_sp->GetObjectFile()->GetFileSpec().GetFilename().IsEmpty())
790 {
791 kernel_name = m_kernel.module_sp->GetObjectFile()->GetFileSpec().GetFilename();
792 }
Jason Molenda31a69612012-10-04 02:16:06 +0000793 strncpy (m_kernel.name, kernel_name.AsCString(), sizeof(m_kernel.name));
794 m_kernel.name[sizeof (m_kernel.name) - 1] = '\0';
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000795
Greg Claytonc859e2d2012-02-13 23:10:39 +0000796 if (m_kernel.address == LLDB_INVALID_ADDRESS)
Greg Clayton7b242382011-07-08 00:48:09 +0000797 {
Jason Molenda6ba6d3d2013-01-30 04:39:32 +0000798 m_kernel.address = m_kernel_load_address;
Greg Claytonc859e2d2012-02-13 23:10:39 +0000799 if (m_kernel.address == LLDB_INVALID_ADDRESS && m_kernel.module_sp)
Greg Clayton7b242382011-07-08 00:48:09 +0000800 {
Greg Claytonc859e2d2012-02-13 23:10:39 +0000801 // We didn't get a hint from the process, so we will
802 // try the kernel at the address that it exists at in
803 // the file if we have one
804 ObjectFile *kernel_object_file = m_kernel.module_sp->GetObjectFile();
805 if (kernel_object_file)
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000806 {
807 addr_t load_address = kernel_object_file->GetHeaderAddress().GetLoadAddress(&m_process->GetTarget());
808 addr_t file_address = kernel_object_file->GetHeaderAddress().GetFileAddress();
809 if (load_address != LLDB_INVALID_ADDRESS && load_address != 0)
810 {
811 m_kernel.address = load_address;
812 if (load_address != file_address)
813 {
814 // Don't accidentally relocate the kernel to the File address --
815 // the Load address has already been set to its actual in-memory address.
816 // Mark it as IsLoaded.
817 m_kernel.load_process_stop_id = m_process->GetStopID();
818 }
819 }
820 else
821 {
822 m_kernel.address = file_address;
823 }
824 }
Greg Clayton7b242382011-07-08 00:48:09 +0000825 }
826 }
Greg Claytonc859e2d2012-02-13 23:10:39 +0000827
828 if (m_kernel.address != LLDB_INVALID_ADDRESS)
Greg Clayton2af282a2012-03-21 04:25:00 +0000829 {
830 if (!m_kernel.LoadImageUsingMemoryModule (m_process))
831 {
832 m_kernel.LoadImageAtFileAddress (m_process);
833 }
834 }
Greg Clayton7b242382011-07-08 00:48:09 +0000835
Jim Ingham28eb5712012-10-12 17:34:26 +0000836 if (m_kernel.IsLoaded() && m_kernel.module_sp)
Greg Clayton7b242382011-07-08 00:48:09 +0000837 {
Greg Claytonc859e2d2012-02-13 23:10:39 +0000838 static ConstString kext_summary_symbol ("gLoadedKextSummaries");
839 const Symbol *symbol = m_kernel.module_sp->FindFirstSymbolWithNameAndType (kext_summary_symbol, eSymbolTypeData);
840 if (symbol)
841 {
Greg Claytone7612132012-03-07 21:03:09 +0000842 m_kext_summary_header_ptr_addr = symbol->GetAddress();
Greg Claytonc859e2d2012-02-13 23:10:39 +0000843 // Update all image infos
844 ReadAllKextSummaries ();
845 }
Greg Clayton7b242382011-07-08 00:48:09 +0000846 }
847 else
Greg Clayton7b242382011-07-08 00:48:09 +0000848 {
Greg Claytonc859e2d2012-02-13 23:10:39 +0000849 m_kernel.Clear(false);
Greg Clayton7b242382011-07-08 00:48:09 +0000850 }
851 }
Greg Clayton7b242382011-07-08 00:48:09 +0000852}
853
Greg Clayton7b242382011-07-08 00:48:09 +0000854//----------------------------------------------------------------------
855// Static callback function that gets called when our DYLD notification
856// breakpoint gets hit. We update all of our image infos and then
857// let our super class DynamicLoader class decide if we should stop
858// or not (based on global preference).
859//----------------------------------------------------------------------
860bool
Greg Clayton944b8282011-08-22 22:30:57 +0000861DynamicLoaderDarwinKernel::BreakpointHitCallback (void *baton,
Greg Clayton374972e2011-07-09 17:15:55 +0000862 StoppointCallbackContext *context,
863 user_id_t break_id,
864 user_id_t break_loc_id)
Greg Clayton0d9fc762011-07-08 03:21:57 +0000865{
Greg Clayton944b8282011-08-22 22:30:57 +0000866 return static_cast<DynamicLoaderDarwinKernel*>(baton)->BreakpointHit (context, break_id, break_loc_id);
Greg Clayton7b242382011-07-08 00:48:09 +0000867}
868
869bool
Greg Clayton944b8282011-08-22 22:30:57 +0000870DynamicLoaderDarwinKernel::BreakpointHit (StoppointCallbackContext *context,
Greg Clayton374972e2011-07-09 17:15:55 +0000871 user_id_t break_id,
872 user_id_t break_loc_id)
873{
Greg Claytond16e1e52011-07-12 17:06:17 +0000874 LogSP log(GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
875 if (log)
Greg Clayton944b8282011-08-22 22:30:57 +0000876 log->Printf ("DynamicLoaderDarwinKernel::BreakpointHit (...)\n");
Greg Claytond16e1e52011-07-12 17:06:17 +0000877
Greg Clayton374972e2011-07-09 17:15:55 +0000878 ReadAllKextSummaries ();
Greg Claytond16e1e52011-07-12 17:06:17 +0000879
880 if (log)
881 PutToLog(log.get());
882
Greg Clayton374972e2011-07-09 17:15:55 +0000883 return GetStopWhenImagesChange();
884}
885
886
887bool
Greg Clayton944b8282011-08-22 22:30:57 +0000888DynamicLoaderDarwinKernel::ReadKextSummaryHeader ()
Greg Clayton7b242382011-07-08 00:48:09 +0000889{
890 Mutex::Locker locker(m_mutex);
891
892 // the all image infos is already valid for this process stop ID
Greg Clayton7b242382011-07-08 00:48:09 +0000893
894 m_kext_summaries.clear();
Greg Claytond16e1e52011-07-12 17:06:17 +0000895 if (m_kext_summary_header_ptr_addr.IsValid())
Greg Clayton7b242382011-07-08 00:48:09 +0000896 {
897 const uint32_t addr_size = m_kernel.GetAddressByteSize ();
898 const ByteOrder byte_order = m_kernel.GetByteOrder();
899 Error error;
900 // Read enough bytes for a "OSKextLoadedKextSummaryHeader" structure
901 // which is currenty 4 uint32_t and a pointer.
902 uint8_t buf[24];
903 DataExtractor data (buf, sizeof(buf), byte_order, addr_size);
904 const size_t count = 4 * sizeof(uint32_t) + addr_size;
Greg Clayton0d9fc762011-07-08 03:21:57 +0000905 const bool prefer_file_cache = false;
Greg Claytond16e1e52011-07-12 17:06:17 +0000906 if (m_process->GetTarget().ReadPointerFromMemory (m_kext_summary_header_ptr_addr,
907 prefer_file_cache,
908 error,
909 m_kext_summary_header_addr))
Greg Clayton7b242382011-07-08 00:48:09 +0000910 {
Greg Claytond16e1e52011-07-12 17:06:17 +0000911 // We got a valid address for our kext summary header and make sure it isn't NULL
912 if (m_kext_summary_header_addr.IsValid() &&
913 m_kext_summary_header_addr.GetFileAddress() != 0)
914 {
915 const size_t bytes_read = m_process->GetTarget().ReadMemory (m_kext_summary_header_addr, prefer_file_cache, buf, count, error);
916 if (bytes_read == count)
917 {
Greg Claytonc7bece562013-01-25 18:06:21 +0000918 lldb::offset_t offset = 0;
Greg Claytona63d08c2011-07-19 03:57:15 +0000919 m_kext_summary_header.version = data.GetU32(&offset);
920 if (m_kext_summary_header.version >= 2)
921 {
922 m_kext_summary_header.entry_size = data.GetU32(&offset);
923 }
924 else
925 {
926 // Versions less than 2 didn't have an entry size, it was hard coded
927 m_kext_summary_header.entry_size = KERNEL_MODULE_ENTRY_SIZE_VERSION_1;
928 }
929 m_kext_summary_header.entry_count = data.GetU32(&offset);
Greg Claytond16e1e52011-07-12 17:06:17 +0000930 return true;
931 }
932 }
Greg Clayton7b242382011-07-08 00:48:09 +0000933 }
934 }
Greg Claytond16e1e52011-07-12 17:06:17 +0000935 m_kext_summary_header_addr.Clear();
Greg Clayton7b242382011-07-08 00:48:09 +0000936 return false;
937}
938
939
940bool
Greg Clayton944b8282011-08-22 22:30:57 +0000941DynamicLoaderDarwinKernel::ParseKextSummaries (const Address &kext_summary_addr,
Greg Clayton0d9fc762011-07-08 03:21:57 +0000942 uint32_t count)
Greg Clayton7b242382011-07-08 00:48:09 +0000943{
944 OSKextLoadedKextSummary::collection kext_summaries;
Greg Clayton374972e2011-07-09 17:15:55 +0000945 LogSP log(GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
Greg Clayton7b242382011-07-08 00:48:09 +0000946 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +0000947 log->Printf ("Adding %d modules.\n", count);
Greg Clayton7b242382011-07-08 00:48:09 +0000948
949 Mutex::Locker locker(m_mutex);
Greg Clayton7b242382011-07-08 00:48:09 +0000950
951 if (!ReadKextSummaries (kext_summary_addr, count, kext_summaries))
952 return false;
953
Greg Clayton07e66e32011-07-20 03:41:06 +0000954 Stream *s = &m_process->GetTarget().GetDebugger().GetOutputStream();
Jason Molenda68b36072012-10-02 03:49:41 +0000955 if (s)
956 s->Printf ("Loading %d kext modules ", count);
Greg Clayton7b242382011-07-08 00:48:09 +0000957 for (uint32_t i = 0; i < count; i++)
958 {
Greg Clayton2af282a2012-03-21 04:25:00 +0000959 if (!kext_summaries[i].LoadImageUsingMemoryModule (m_process))
960 kext_summaries[i].LoadImageAtFileAddress (m_process);
Greg Claytonc859e2d2012-02-13 23:10:39 +0000961
Greg Clayton5b882162011-07-21 01:12:01 +0000962 if (s)
Jason Molenda68b36072012-10-02 03:49:41 +0000963 s->Printf (".");
964
Greg Claytona63d08c2011-07-19 03:57:15 +0000965 if (log)
966 kext_summaries[i].PutToLog (log.get());
Greg Clayton7b242382011-07-08 00:48:09 +0000967 }
Jason Molenda68b36072012-10-02 03:49:41 +0000968 if (s)
969 {
970 s->Printf (" done.\n");
971 s->Flush ();
972 }
973
Greg Clayton7b242382011-07-08 00:48:09 +0000974 bool return_value = AddModulesUsingImageInfos (kext_summaries);
Greg Clayton7b242382011-07-08 00:48:09 +0000975 return return_value;
976}
977
978// Adds the modules in image_infos to m_kext_summaries.
979// NB don't call this passing in m_kext_summaries.
980
981bool
Greg Clayton944b8282011-08-22 22:30:57 +0000982DynamicLoaderDarwinKernel::AddModulesUsingImageInfos (OSKextLoadedKextSummary::collection &image_infos)
Greg Clayton7b242382011-07-08 00:48:09 +0000983{
984 // Now add these images to the main list.
985 ModuleList loaded_module_list;
Greg Clayton7b242382011-07-08 00:48:09 +0000986
987 for (uint32_t idx = 0; idx < image_infos.size(); ++idx)
988 {
Greg Claytonc859e2d2012-02-13 23:10:39 +0000989 OSKextLoadedKextSummary &image_info = image_infos[idx];
990 m_kext_summaries.push_back(image_info);
Greg Clayton7b242382011-07-08 00:48:09 +0000991
Greg Claytonc859e2d2012-02-13 23:10:39 +0000992 if (image_info.module_sp && m_process->GetStopID() == image_info.load_process_stop_id)
993 loaded_module_list.AppendIfNeeded (image_infos[idx].module_sp);
Greg Clayton7b242382011-07-08 00:48:09 +0000994 }
995
Enrico Granata17598482012-11-08 02:22:02 +0000996 m_process->GetTarget().ModulesDidLoad (loaded_module_list);
Greg Clayton7b242382011-07-08 00:48:09 +0000997 return true;
998}
999
Greg Clayton7b242382011-07-08 00:48:09 +00001000
1001uint32_t
Greg Clayton944b8282011-08-22 22:30:57 +00001002DynamicLoaderDarwinKernel::ReadKextSummaries (const Address &kext_summary_addr,
Greg Clayton7b242382011-07-08 00:48:09 +00001003 uint32_t image_infos_count,
1004 OSKextLoadedKextSummary::collection &image_infos)
1005{
1006 const ByteOrder endian = m_kernel.GetByteOrder();
1007 const uint32_t addr_size = m_kernel.GetAddressByteSize();
1008
1009 image_infos.resize(image_infos_count);
1010 const size_t count = image_infos.size() * m_kext_summary_header.entry_size;
1011 DataBufferHeap data(count, 0);
1012 Error error;
Greg Clayton5b882162011-07-21 01:12:01 +00001013
Greg Clayton0d9fc762011-07-08 03:21:57 +00001014 const bool prefer_file_cache = false;
1015 const size_t bytes_read = m_process->GetTarget().ReadMemory (kext_summary_addr,
1016 prefer_file_cache,
1017 data.GetBytes(),
1018 data.GetByteSize(),
1019 error);
Greg Clayton7b242382011-07-08 00:48:09 +00001020 if (bytes_read == count)
1021 {
Greg Claytona63d08c2011-07-19 03:57:15 +00001022
Greg Clayton7b242382011-07-08 00:48:09 +00001023 DataExtractor extractor (data.GetBytes(), data.GetByteSize(), endian, addr_size);
1024 uint32_t i=0;
Greg Claytona63d08c2011-07-19 03:57:15 +00001025 for (uint32_t kext_summary_offset = 0;
1026 i < image_infos.size() && extractor.ValidOffsetForDataOfSize(kext_summary_offset, m_kext_summary_header.entry_size);
1027 ++i, kext_summary_offset += m_kext_summary_header.entry_size)
Greg Clayton7b242382011-07-08 00:48:09 +00001028 {
Greg Claytonc7bece562013-01-25 18:06:21 +00001029 lldb::offset_t offset = kext_summary_offset;
Greg Clayton7b242382011-07-08 00:48:09 +00001030 const void *name_data = extractor.GetData(&offset, KERNEL_MODULE_MAX_NAME);
1031 if (name_data == NULL)
1032 break;
1033 memcpy (image_infos[i].name, name_data, KERNEL_MODULE_MAX_NAME);
1034 image_infos[i].uuid.SetBytes(extractor.GetData (&offset, 16));
1035 image_infos[i].address = extractor.GetU64(&offset);
Greg Clayton0d9fc762011-07-08 03:21:57 +00001036 if (!image_infos[i].so_address.SetLoadAddress (image_infos[i].address, &m_process->GetTarget()))
1037 m_process->GetTarget().GetImages().ResolveFileAddress (image_infos[i].address, image_infos[i].so_address);
Greg Clayton7b242382011-07-08 00:48:09 +00001038 image_infos[i].size = extractor.GetU64(&offset);
1039 image_infos[i].version = extractor.GetU64(&offset);
1040 image_infos[i].load_tag = extractor.GetU32(&offset);
1041 image_infos[i].flags = extractor.GetU32(&offset);
Greg Claytona63d08c2011-07-19 03:57:15 +00001042 if ((offset - kext_summary_offset) < m_kext_summary_header.entry_size)
1043 {
1044 image_infos[i].reference_list = extractor.GetU64(&offset);
1045 }
1046 else
1047 {
1048 image_infos[i].reference_list = 0;
1049 }
Greg Clayton7b242382011-07-08 00:48:09 +00001050 }
1051 if (i < image_infos.size())
1052 image_infos.resize(i);
1053 }
1054 else
1055 {
1056 image_infos.clear();
1057 }
1058 return image_infos.size();
1059}
1060
1061bool
Greg Clayton944b8282011-08-22 22:30:57 +00001062DynamicLoaderDarwinKernel::ReadAllKextSummaries ()
Greg Clayton7b242382011-07-08 00:48:09 +00001063{
Greg Clayton374972e2011-07-09 17:15:55 +00001064 LogSP log(GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
Greg Clayton7b242382011-07-08 00:48:09 +00001065
1066 Mutex::Locker locker(m_mutex);
Greg Clayton374972e2011-07-09 17:15:55 +00001067
Greg Clayton7b242382011-07-08 00:48:09 +00001068 if (ReadKextSummaryHeader ())
1069 {
Greg Clayton374972e2011-07-09 17:15:55 +00001070 if (m_kext_summary_header.entry_count > 0 && m_kext_summary_header_addr.IsValid())
Greg Clayton7b242382011-07-08 00:48:09 +00001071 {
Greg Clayton0d9fc762011-07-08 03:21:57 +00001072 Address summary_addr (m_kext_summary_header_addr);
Greg Claytona63d08c2011-07-19 03:57:15 +00001073 summary_addr.Slide(m_kext_summary_header.GetSize());
Greg Clayton0d9fc762011-07-08 03:21:57 +00001074 if (!ParseKextSummaries (summary_addr, m_kext_summary_header.entry_count))
Greg Clayton7b242382011-07-08 00:48:09 +00001075 {
Greg Clayton7b242382011-07-08 00:48:09 +00001076 m_kext_summaries.clear();
1077 }
1078 return true;
1079 }
1080 }
1081 return false;
1082}
1083
1084//----------------------------------------------------------------------
Greg Clayton7b242382011-07-08 00:48:09 +00001085// Dump an image info structure to the file handle provided.
1086//----------------------------------------------------------------------
1087void
Greg Clayton944b8282011-08-22 22:30:57 +00001088DynamicLoaderDarwinKernel::OSKextLoadedKextSummary::PutToLog (Log *log) const
Greg Clayton7b242382011-07-08 00:48:09 +00001089{
1090 if (log == NULL)
1091 return;
Greg Clayton07e66e32011-07-20 03:41:06 +00001092 const uint8_t *u = (uint8_t *)uuid.GetBytes();
Greg Clayton7b242382011-07-08 00:48:09 +00001093
1094 if (address == LLDB_INVALID_ADDRESS)
1095 {
1096 if (u)
1097 {
Greg Claytona63d08c2011-07-19 03:57:15 +00001098 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)",
Greg Clayton7b242382011-07-08 00:48:09 +00001099 u[ 0], u[ 1], u[ 2], u[ 3],
1100 u[ 4], u[ 5], u[ 6], u[ 7],
1101 u[ 8], u[ 9], u[10], u[11],
1102 u[12], u[13], u[14], u[15],
1103 name);
1104 }
1105 else
Greg Claytona63d08c2011-07-19 03:57:15 +00001106 log->Printf("\tname=\"%s\" (UNLOADED)", name);
Greg Clayton7b242382011-07-08 00:48:09 +00001107 }
1108 else
1109 {
1110 if (u)
1111 {
Daniel Malead01b2952012-11-29 21:49:15 +00001112 log->Printf("\taddr=0x%16.16" PRIx64 " size=0x%16.16" PRIx64 " version=0x%16.16" PRIx64 " load-tag=0x%8.8x flags=0x%8.8x ref-list=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\"",
Greg Claytona63d08c2011-07-19 03:57:15 +00001113 address, size, version, load_tag, flags, reference_list,
1114 u[ 0], u[ 1], u[ 2], u[ 3], u[ 4], u[ 5], u[ 6], u[ 7],
1115 u[ 8], u[ 9], u[10], u[11], u[12], u[13], u[14], u[15],
Greg Clayton7b242382011-07-08 00:48:09 +00001116 name);
1117 }
1118 else
1119 {
Daniel Malead01b2952012-11-29 21:49:15 +00001120 log->Printf("\t[0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ") version=0x%16.16" PRIx64 " load-tag=0x%8.8x flags=0x%8.8x ref-list=0x%16.16" PRIx64 " name=\"%s\"",
Greg Claytona63d08c2011-07-19 03:57:15 +00001121 address, address+size, version, load_tag, flags, reference_list,
1122 name);
Greg Clayton7b242382011-07-08 00:48:09 +00001123 }
Greg Clayton7b242382011-07-08 00:48:09 +00001124 }
1125}
1126
1127//----------------------------------------------------------------------
1128// Dump the _dyld_all_image_infos members and all current image infos
1129// that we have parsed to the file handle provided.
1130//----------------------------------------------------------------------
1131void
Greg Clayton944b8282011-08-22 22:30:57 +00001132DynamicLoaderDarwinKernel::PutToLog(Log *log) const
Greg Clayton7b242382011-07-08 00:48:09 +00001133{
1134 if (log == NULL)
1135 return;
1136
1137 Mutex::Locker locker(m_mutex);
Daniel Malead01b2952012-11-29 21:49:15 +00001138 log->Printf("gLoadedKextSummaries = 0x%16.16" PRIx64 " { version=%u, entry_size=%u, entry_count=%u }",
Greg Clayton0d9fc762011-07-08 03:21:57 +00001139 m_kext_summary_header_addr.GetFileAddress(),
Greg Clayton7b242382011-07-08 00:48:09 +00001140 m_kext_summary_header.version,
1141 m_kext_summary_header.entry_size,
Greg Claytona63d08c2011-07-19 03:57:15 +00001142 m_kext_summary_header.entry_count);
Greg Clayton7b242382011-07-08 00:48:09 +00001143
1144 size_t i;
1145 const size_t count = m_kext_summaries.size();
1146 if (count > 0)
1147 {
1148 log->PutCString("Loaded:");
1149 for (i = 0; i<count; i++)
1150 m_kext_summaries[i].PutToLog(log);
1151 }
1152}
1153
1154void
Greg Clayton944b8282011-08-22 22:30:57 +00001155DynamicLoaderDarwinKernel::PrivateInitialize(Process *process)
Greg Clayton7b242382011-07-08 00:48:09 +00001156{
Greg Clayton944b8282011-08-22 22:30:57 +00001157 DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState()));
Greg Clayton7b242382011-07-08 00:48:09 +00001158 Clear(true);
1159 m_process = process;
Greg Clayton7b242382011-07-08 00:48:09 +00001160}
1161
Greg Clayton374972e2011-07-09 17:15:55 +00001162void
Greg Clayton944b8282011-08-22 22:30:57 +00001163DynamicLoaderDarwinKernel::SetNotificationBreakpointIfNeeded ()
Greg Clayton7b242382011-07-08 00:48:09 +00001164{
Greg Claytonc859e2d2012-02-13 23:10:39 +00001165 if (m_break_id == LLDB_INVALID_BREAK_ID && m_kernel.module_sp)
Greg Clayton374972e2011-07-09 17:15:55 +00001166 {
Greg Clayton944b8282011-08-22 22:30:57 +00001167 DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState()));
Greg Clayton374972e2011-07-09 17:15:55 +00001168
Greg Claytond16e1e52011-07-12 17:06:17 +00001169
Jim Inghama8558b62012-05-22 00:12:20 +00001170 const bool internal_bp = true;
Greg Claytond16e1e52011-07-12 17:06:17 +00001171 const LazyBool skip_prologue = eLazyBoolNo;
Jim Ingham969795f2011-09-21 01:17:13 +00001172 FileSpecList module_spec_list;
1173 module_spec_list.Append (m_kernel.module_sp->GetFileSpec());
1174 Breakpoint *bp = m_process->GetTarget().CreateBreakpoint (&module_spec_list,
Jim Ingham87df91b2011-09-23 00:54:11 +00001175 NULL,
Greg Clayton374972e2011-07-09 17:15:55 +00001176 "OSKextLoadedKextSummariesUpdated",
1177 eFunctionNameTypeFull,
Jim Inghama8558b62012-05-22 00:12:20 +00001178 skip_prologue,
1179 internal_bp).get();
Greg Clayton374972e2011-07-09 17:15:55 +00001180
Greg Clayton944b8282011-08-22 22:30:57 +00001181 bp->SetCallback (DynamicLoaderDarwinKernel::BreakpointHitCallback, this, true);
Greg Clayton374972e2011-07-09 17:15:55 +00001182 m_break_id = bp->GetID();
1183 }
Greg Clayton7b242382011-07-08 00:48:09 +00001184}
1185
1186//----------------------------------------------------------------------
1187// Member function that gets called when the process state changes.
1188//----------------------------------------------------------------------
1189void
Greg Clayton944b8282011-08-22 22:30:57 +00001190DynamicLoaderDarwinKernel::PrivateProcessStateChanged (Process *process, StateType state)
Greg Clayton7b242382011-07-08 00:48:09 +00001191{
Greg Clayton944b8282011-08-22 22:30:57 +00001192 DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s(%s)\n", __FUNCTION__, StateAsCString(state));
Greg Clayton7b242382011-07-08 00:48:09 +00001193 switch (state)
1194 {
1195 case eStateConnected:
1196 case eStateAttaching:
1197 case eStateLaunching:
1198 case eStateInvalid:
1199 case eStateUnloaded:
1200 case eStateExited:
1201 case eStateDetached:
1202 Clear(false);
1203 break;
1204
1205 case eStateStopped:
Greg Clayton374972e2011-07-09 17:15:55 +00001206 UpdateIfNeeded();
Greg Clayton7b242382011-07-08 00:48:09 +00001207 break;
1208
1209 case eStateRunning:
1210 case eStateStepping:
1211 case eStateCrashed:
1212 case eStateSuspended:
1213 break;
Greg Clayton7b242382011-07-08 00:48:09 +00001214 }
1215}
1216
1217ThreadPlanSP
Greg Clayton944b8282011-08-22 22:30:57 +00001218DynamicLoaderDarwinKernel::GetStepThroughTrampolinePlan (Thread &thread, bool stop_others)
Greg Clayton7b242382011-07-08 00:48:09 +00001219{
1220 ThreadPlanSP thread_plan_sp;
Greg Clayton374972e2011-07-09 17:15:55 +00001221 LogSP log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1222 if (log)
1223 log->Printf ("Could not find symbol for step through.");
Greg Clayton7b242382011-07-08 00:48:09 +00001224 return thread_plan_sp;
1225}
1226
1227Error
Greg Clayton944b8282011-08-22 22:30:57 +00001228DynamicLoaderDarwinKernel::CanLoadImage ()
Greg Clayton7b242382011-07-08 00:48:09 +00001229{
1230 Error error;
1231 error.SetErrorString("always unsafe to load or unload shared libraries in the darwin kernel");
1232 return error;
1233}
1234
1235void
Greg Clayton944b8282011-08-22 22:30:57 +00001236DynamicLoaderDarwinKernel::Initialize()
Greg Clayton7b242382011-07-08 00:48:09 +00001237{
1238 PluginManager::RegisterPlugin (GetPluginNameStatic(),
1239 GetPluginDescriptionStatic(),
Greg Claytone8cd0c92012-10-19 18:02:49 +00001240 CreateInstance,
1241 DebuggerInitialize);
Greg Clayton7b242382011-07-08 00:48:09 +00001242}
1243
1244void
Greg Clayton944b8282011-08-22 22:30:57 +00001245DynamicLoaderDarwinKernel::Terminate()
Greg Clayton7b242382011-07-08 00:48:09 +00001246{
1247 PluginManager::UnregisterPlugin (CreateInstance);
1248}
1249
Greg Claytone8cd0c92012-10-19 18:02:49 +00001250void
1251DynamicLoaderDarwinKernel::DebuggerInitialize (lldb_private::Debugger &debugger)
1252{
1253 if (!PluginManager::GetSettingForDynamicLoaderPlugin (debugger, DynamicLoaderDarwinKernelProperties::GetSettingName()))
1254 {
1255 const bool is_global_setting = true;
1256 PluginManager::CreateSettingForDynamicLoaderPlugin (debugger,
1257 GetGlobalProperties()->GetValueProperties(),
1258 ConstString ("Properties for the DynamicLoaderDarwinKernel plug-in."),
1259 is_global_setting);
1260 }
1261}
Greg Clayton7b242382011-07-08 00:48:09 +00001262
1263const char *
Greg Clayton944b8282011-08-22 22:30:57 +00001264DynamicLoaderDarwinKernel::GetPluginNameStatic()
Greg Clayton7b242382011-07-08 00:48:09 +00001265{
Greg Clayton468ea4e2012-10-19 18:14:47 +00001266 return "dynamic-loader.darwin-kernel";
Greg Clayton7b242382011-07-08 00:48:09 +00001267}
1268
1269const char *
Greg Clayton944b8282011-08-22 22:30:57 +00001270DynamicLoaderDarwinKernel::GetPluginDescriptionStatic()
Greg Clayton7b242382011-07-08 00:48:09 +00001271{
1272 return "Dynamic loader plug-in that watches for shared library loads/unloads in the MacOSX kernel.";
1273}
1274
1275
1276//------------------------------------------------------------------
1277// PluginInterface protocol
1278//------------------------------------------------------------------
1279const char *
Greg Clayton944b8282011-08-22 22:30:57 +00001280DynamicLoaderDarwinKernel::GetPluginName()
Greg Clayton7b242382011-07-08 00:48:09 +00001281{
Greg Clayton944b8282011-08-22 22:30:57 +00001282 return "DynamicLoaderDarwinKernel";
Greg Clayton7b242382011-07-08 00:48:09 +00001283}
1284
1285const char *
Greg Clayton944b8282011-08-22 22:30:57 +00001286DynamicLoaderDarwinKernel::GetShortPluginName()
Greg Clayton7b242382011-07-08 00:48:09 +00001287{
1288 return GetPluginNameStatic();
1289}
1290
1291uint32_t
Greg Clayton944b8282011-08-22 22:30:57 +00001292DynamicLoaderDarwinKernel::GetPluginVersion()
Greg Clayton7b242382011-07-08 00:48:09 +00001293{
1294 return 1;
1295}
1296
Greg Clayton1f746072012-08-29 21:13:06 +00001297lldb::ByteOrder
1298DynamicLoaderDarwinKernel::GetByteOrderFromMagic (uint32_t magic)
1299{
1300 switch (magic)
1301 {
1302 case llvm::MachO::HeaderMagic32:
1303 case llvm::MachO::HeaderMagic64:
1304 return lldb::endian::InlHostByteOrder();
1305
1306 case llvm::MachO::HeaderMagic32Swapped:
1307 case llvm::MachO::HeaderMagic64Swapped:
1308 if (lldb::endian::InlHostByteOrder() == lldb::eByteOrderBig)
1309 return lldb::eByteOrderLittle;
1310 else
1311 return lldb::eByteOrderBig;
1312
1313 default:
1314 break;
1315 }
1316 return lldb::eByteOrderInvalid;
1317}
1318