blob: d913a797288ede330dd8423b7fd7ca5a340c82e1 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- DynamicLoaderMacOSXDYLD.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/Breakpoint/StoppointCallbackContext.h"
11#include "lldb/Core/DataBuffer.h"
12#include "lldb/Core/DataBufferHeap.h"
13#include "lldb/Core/Log.h"
14#include "lldb/Core/Module.h"
15#include "lldb/Core/PluginManager.h"
16#include "lldb/Core/State.h"
17#include "lldb/Symbol/ObjectFile.h"
Jim Inghamb66cd072010-09-28 01:25:32 +000018#include "lldb/Target/ObjCLanguageRuntime.h"
Chris Lattner24943d22010-06-08 16:52:24 +000019#include "lldb/Target/RegisterContext.h"
20#include "lldb/Target/Target.h"
21#include "lldb/Target/Thread.h"
22#include "lldb/Target/ThreadPlanRunToAddress.h"
23#include "lldb/Target/StackFrame.h"
24
25#include "DynamicLoaderMacOSXDYLD.h"
Chris Lattner24943d22010-06-08 16:52:24 +000026
27//#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN
28#ifdef ENABLE_DEBUG_PRINTF
29#include <stdio.h>
30#define DEBUG_PRINTF(fmt, ...) printf(fmt, ## __VA_ARGS__)
31#else
32#define DEBUG_PRINTF(fmt, ...)
33#endif
34
35using namespace lldb;
36using namespace lldb_private;
Greg Clayton1674b122010-07-21 22:12:05 +000037using namespace llvm::MachO;
Chris Lattner24943d22010-06-08 16:52:24 +000038
39/// FIXME - The ObjC Runtime trampoline handler doesn't really belong here.
40/// I am putting it here so I can invoke it in the Trampoline code here, but
41/// it should be moved to the ObjC Runtime support when it is set up.
42
Greg Claytonab429022010-12-12 21:03:32 +000043
44DynamicLoaderMacOSXDYLD::DYLDImageInfo *
45DynamicLoaderMacOSXDYLD::GetImageInfo (const FileSpec &file_spec, const UUID &uuid)
46{
47 DYLDImageInfo::collection::iterator pos, end = m_dyld_image_infos.end();
48 for (pos = m_dyld_image_infos.begin(); pos != end; ++pos)
49 {
50 if (pos->uuid == uuid && pos->file_spec == file_spec)
51 return &(*pos);
52 }
53
54 if (m_dyld.uuid == uuid && m_dyld.file_spec == file_spec)
55 return &m_dyld;
56
57 return NULL;
58}
59
Chris Lattner24943d22010-06-08 16:52:24 +000060//----------------------------------------------------------------------
61// Create an instance of this class. This function is filled into
62// the plugin info class that gets handed out by the plugin factory and
63// allows the lldb to instantiate an instance of this class.
64//----------------------------------------------------------------------
65DynamicLoader *
66DynamicLoaderMacOSXDYLD::CreateInstance (Process* process)
67{
68 return new DynamicLoaderMacOSXDYLD (process);
69}
70
71//----------------------------------------------------------------------
72// Constructor
73//----------------------------------------------------------------------
74DynamicLoaderMacOSXDYLD::DynamicLoaderMacOSXDYLD (Process* process) :
75 DynamicLoader(process),
76 m_dyld(),
77 m_dyld_all_image_infos_addr(LLDB_INVALID_ADDRESS),
78 m_dyld_all_image_infos(),
Greg Clayton20d338f2010-11-18 05:57:03 +000079 m_dyld_all_image_infos_stop_id (UINT32_MAX),
Chris Lattner24943d22010-06-08 16:52:24 +000080 m_break_id(LLDB_INVALID_BREAK_ID),
81 m_dyld_image_infos(),
Greg Clayton20d338f2010-11-18 05:57:03 +000082 m_dyld_image_infos_stop_id (UINT32_MAX),
Jim Inghamb66cd072010-09-28 01:25:32 +000083 m_mutex(Mutex::eMutexTypeRecursive)
Chris Lattner24943d22010-06-08 16:52:24 +000084{
85}
86
87//----------------------------------------------------------------------
88// Destructor
89//----------------------------------------------------------------------
90DynamicLoaderMacOSXDYLD::~DynamicLoaderMacOSXDYLD()
91{
92 Clear(true);
93}
94
95//------------------------------------------------------------------
96/// Called after attaching a process.
97///
98/// Allow DynamicLoader plug-ins to execute some code after
99/// attaching to a process.
100//------------------------------------------------------------------
101void
102DynamicLoaderMacOSXDYLD::DidAttach ()
103{
104 PrivateInitialize(m_process);
Greg Clayton20d338f2010-11-18 05:57:03 +0000105 LocateDYLD ();
Chris Lattner24943d22010-06-08 16:52:24 +0000106 SetNotificationBreakpoint ();
Chris Lattner24943d22010-06-08 16:52:24 +0000107}
108
109//------------------------------------------------------------------
110/// Called after attaching a process.
111///
112/// Allow DynamicLoader plug-ins to execute some code after
113/// attaching to a process.
114//------------------------------------------------------------------
115void
116DynamicLoaderMacOSXDYLD::DidLaunch ()
117{
118 PrivateInitialize(m_process);
Greg Clayton20d338f2010-11-18 05:57:03 +0000119 LocateDYLD ();
Chris Lattner24943d22010-06-08 16:52:24 +0000120 SetNotificationBreakpoint ();
Chris Lattner24943d22010-06-08 16:52:24 +0000121}
122
123
124//----------------------------------------------------------------------
125// Clear out the state of this class.
126//----------------------------------------------------------------------
127void
128DynamicLoaderMacOSXDYLD::Clear (bool clear_process)
129{
130 Mutex::Locker locker(m_mutex);
131
132 if (m_process->IsAlive() && LLDB_BREAK_ID_IS_VALID(m_break_id))
133 m_process->ClearBreakpointSiteByID(m_break_id);
134
135 if (clear_process)
136 m_process = NULL;
137 m_dyld.Clear(false);
138 m_dyld_all_image_infos_addr = LLDB_INVALID_ADDRESS;
139 m_dyld_all_image_infos.Clear();
140 m_break_id = LLDB_INVALID_BREAK_ID;
141 m_dyld_image_infos.clear();
142}
143
144//----------------------------------------------------------------------
145// Check if we have found DYLD yet
146//----------------------------------------------------------------------
147bool
148DynamicLoaderMacOSXDYLD::DidSetNotificationBreakpoint() const
149{
150 return LLDB_BREAK_ID_IS_VALID (m_break_id);
151}
152
153//----------------------------------------------------------------------
154// Try and figure out where dyld is by first asking the Process
155// if it knows (which currently calls down in the the lldb::Process
156// to get the DYLD info (available on SnowLeopard only). If that fails,
157// then check in the default addresses.
158//----------------------------------------------------------------------
159bool
160DynamicLoaderMacOSXDYLD::LocateDYLD()
161{
162 if (m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS)
163 m_dyld_all_image_infos_addr = m_process->GetImageInfoAddress ();
164
165 if (m_dyld_all_image_infos_addr != LLDB_INVALID_ADDRESS)
166 {
167 if (ReadAllImageInfosStructure ())
168 {
169 if (m_dyld_all_image_infos.dyldImageLoadAddress != LLDB_INVALID_ADDRESS)
170 return ReadDYLDInfoFromMemoryAndSetNotificationCallback (m_dyld_all_image_infos.dyldImageLoadAddress);
171 else
172 return ReadDYLDInfoFromMemoryAndSetNotificationCallback (m_dyld_all_image_infos_addr & 0xfffffffffff00000ull);
173 }
174 }
175
176 // Check some default values
177 Module *executable = m_process->GetTarget().GetExecutableModule().get();
178
179 if (executable)
180 {
181 if (executable->GetArchitecture().GetAddressByteSize() == 8)
182 {
183 return ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x7fff5fc00000ull);
184 }
185#if defined (__arm__)
186 else
187 {
188 ArchSpec arm_arch("arm");
189 if (arm_arch == executable->Arch())
190 return ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x2fe00000);
191 }
192#endif
193 return ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x8fe00000);
194 }
195 return false;
196}
197
198//----------------------------------------------------------------------
199// Assume that dyld is in memory at ADDR and try to parse it's load
200// commands
201//----------------------------------------------------------------------
202bool
203DynamicLoaderMacOSXDYLD::ReadDYLDInfoFromMemoryAndSetNotificationCallback(lldb::addr_t addr)
204{
205 DataExtractor data; // Load command data
206 if (ReadMachHeader (addr, &m_dyld.header, &data))
207 {
Greg Clayton1674b122010-07-21 22:12:05 +0000208 if (m_dyld.header.filetype == HeaderFileTypeDynamicLinkEditor)
Chris Lattner24943d22010-06-08 16:52:24 +0000209 {
210 m_dyld.address = addr;
211 ModuleSP dyld_module_sp;
212 if (ParseLoadCommands (data, m_dyld, &m_dyld.file_spec))
213 {
214 if (m_dyld.file_spec)
215 {
Greg Claytoncf015052010-06-11 03:25:34 +0000216 ArchSpec dyld_arch(eArchTypeMachO, m_dyld.header.cputype, m_dyld.header.cpusubtype);
Chris Lattner24943d22010-06-08 16:52:24 +0000217 dyld_module_sp = m_process->GetTarget().GetImages().FindFirstModuleForFileSpec (m_dyld.file_spec);
218
219 if (dyld_module_sp.get() == NULL || dyld_module_sp->GetArchitecture() != dyld_arch)
220 {
221 dyld_module_sp = m_process->GetTarget().GetSharedModule (m_dyld.file_spec,
222 dyld_arch,
223 &m_dyld.uuid);
224 }
225
226 UpdateImageLoadAddress(dyld_module_sp.get(), m_dyld);
227 }
228 }
229
230 if (m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS && dyld_module_sp.get())
231 {
232 static ConstString g_dyld_all_image_infos ("dyld_all_image_infos");
233 const Symbol *symbol = dyld_module_sp->FindFirstSymbolWithNameAndType (g_dyld_all_image_infos, eSymbolTypeData);
234 if (symbol)
Greg Claytoneea26402010-09-14 23:36:40 +0000235 m_dyld_all_image_infos_addr = symbol->GetValue().GetLoadAddress(&m_process->GetTarget());
Chris Lattner24943d22010-06-08 16:52:24 +0000236 }
237
238 // Update all image infos
239 UpdateAllImageInfos();
240
241 // If we didn't have an executable before, but now we do, then the
242 // dyld module shared pointer might be unique and we may need to add
243 // it again (since Target::SetExecutableModule() will clear the
244 // images). So append the dyld module back to the list if it is
245 /// unique!
Greg Claytonab429022010-12-12 21:03:32 +0000246 if (m_process->GetTarget().GetImages().AppendIfNeeded (dyld_module_sp))
Chris Lattner24943d22010-06-08 16:52:24 +0000247 UpdateImageLoadAddress(dyld_module_sp.get(), m_dyld);
248
249 return true;
250 }
251 }
252 return false;
253}
254
255bool
256DynamicLoaderMacOSXDYLD::NeedToLocateDYLD () const
257{
258 return m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS;
259}
260
261bool
262DynamicLoaderMacOSXDYLD::UpdateCommPageLoadAddress(Module *module)
263{
264 bool changed = false;
265 if (module)
266 {
267 ObjectFile *image_object_file = module->GetObjectFile();
268 if (image_object_file)
269 {
270 SectionList *section_list = image_object_file->GetSectionList ();
271 if (section_list)
272 {
273 uint32_t num_sections = section_list->GetSize();
274 for (uint32_t i=0; i<num_sections; ++i)
275 {
276 Section* section = section_list->GetSectionAtIndex (i).get();
277 if (section)
278 {
279 const addr_t new_section_load_addr = section->GetFileAddress ();
Greg Claytoneea26402010-09-14 23:36:40 +0000280 const addr_t old_section_load_addr = m_process->GetTarget().GetSectionLoadList().GetSectionLoadAddress (section);
Chris Lattner24943d22010-06-08 16:52:24 +0000281 if (old_section_load_addr == LLDB_INVALID_ADDRESS ||
282 old_section_load_addr != new_section_load_addr)
283 {
Greg Claytoneea26402010-09-14 23:36:40 +0000284 if (m_process->GetTarget().GetSectionLoadList().SetSectionLoadAddress (section, section->GetFileAddress ()))
Chris Lattner24943d22010-06-08 16:52:24 +0000285 changed = true;
286 }
287 }
288 }
289 }
290 }
291 }
292 return changed;
293}
294
295//----------------------------------------------------------------------
296// Update the load addresses for all segments in MODULE using the
297// updated INFO that is passed in.
298//----------------------------------------------------------------------
299bool
300DynamicLoaderMacOSXDYLD::UpdateImageLoadAddress (Module *module, struct DYLDImageInfo& info)
301{
302 bool changed = false;
303 if (module)
304 {
305 ObjectFile *image_object_file = module->GetObjectFile();
306 if (image_object_file)
307 {
308 SectionList *section_list = image_object_file->GetSectionList ();
309 if (section_list)
310 {
311 // All sections listed in the dyld image info structure will all
312 // either be fixed up already, or they will all be off by a single
313 // slide amount that is determined by finding the first segment
314 // that is at file offset zero which also has bytes (a file size
315 // that is greater than zero) in the object file.
316
317 // Determine the slide amount (if any)
318 info.slide = 0;
319 const size_t num_sections = section_list->GetSize();
320 size_t sect_idx = 0;
321 for (sect_idx = 0; sect_idx < num_sections; ++sect_idx)
322 {
323 // Iterate through the object file sections to find the
324 // first section that starts of file offset zero and that
325 // has bytes in the file...
326 Section *section = section_list->GetSectionAtIndex (sect_idx).get();
327 if (section)
328 {
329 // Find the first section that begins at file offset zero
330 // a file size (skip page zero).
331 if (section->GetFileOffset() == 0 && section->GetFileSize() > 0)
332 {
333 // We have now found the section, lets match it up
334 // with the section in the dyld image info structure.
335 const Segment *dyld_segment = info.FindSegment (section->GetName());
336 if (dyld_segment)
337 info.slide = info.address - dyld_segment->addr;
338 // We have found the slide amount, so we can exit
339 // this for loop.
340 break;
341 }
342 }
343 }
344
345 // We now know the slide amount, so go through all sections
346 // and update the load addresses with the correct values.
347 uint32_t num_segments = info.segments.size();
348 for (uint32_t i=0; i<num_segments; ++i)
349 {
350 SectionSP section_sp(section_list->FindSectionByName(info.segments[i].name));
351 assert (section_sp.get() != NULL);
352 const addr_t new_section_load_addr = info.segments[i].addr + info.slide;
Greg Claytoneea26402010-09-14 23:36:40 +0000353 const addr_t old_section_load_addr = m_process->GetTarget().GetSectionLoadList().GetSectionLoadAddress (section_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +0000354 if (old_section_load_addr == LLDB_INVALID_ADDRESS ||
355 old_section_load_addr != new_section_load_addr)
356 {
Greg Claytoneea26402010-09-14 23:36:40 +0000357 if (m_process->GetTarget().GetSectionLoadList().SetSectionLoadAddress (section_sp.get(), new_section_load_addr))
Chris Lattner24943d22010-06-08 16:52:24 +0000358 changed = true;
359 }
360 }
361 }
362 }
363 }
364 return changed;
365}
366
367//----------------------------------------------------------------------
368// Update the load addresses for all segments in MODULE using the
369// updated INFO that is passed in.
370//----------------------------------------------------------------------
371bool
372DynamicLoaderMacOSXDYLD::UnloadImageLoadAddress (Module *module, struct DYLDImageInfo& info)
373{
374 bool changed = false;
375 if (module)
376 {
377 ObjectFile *image_object_file = module->GetObjectFile();
378 if (image_object_file)
379 {
380 SectionList *section_list = image_object_file->GetSectionList ();
381 if (section_list)
382 {
383 uint32_t num_segments = info.segments.size();
384 for (uint32_t i=0; i<num_segments; ++i)
385 {
386 SectionSP section_sp(section_list->FindSectionByName(info.segments[i].name));
387 assert (section_sp.get() != NULL);
388 const addr_t old_section_load_addr = info.segments[i].addr + info.slide;
Greg Claytoneea26402010-09-14 23:36:40 +0000389 if (m_process->GetTarget().GetSectionLoadList().SetSectionUnloaded (section_sp.get(), old_section_load_addr))
Chris Lattner24943d22010-06-08 16:52:24 +0000390 changed = true;
391 }
392 }
393 }
394 }
395 return changed;
396}
397
398
399//----------------------------------------------------------------------
400// Static callback function that gets called when our DYLD notification
401// breakpoint gets hit. We update all of our image infos and then
402// let our super class DynamicLoader class decide if we should stop
403// or not (based on global preference).
404//----------------------------------------------------------------------
405bool
406DynamicLoaderMacOSXDYLD::NotifyBreakpointHit (void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, lldb::user_id_t break_loc_id)
407{
408 // Let the event know that the images have changed
409 DynamicLoaderMacOSXDYLD* dyld_instance = (DynamicLoaderMacOSXDYLD*) baton;
410 dyld_instance->UpdateAllImageInfos();
411 // Return true to stop the target, false to just let the target run
412 return dyld_instance->GetStopWhenImagesChange();
413}
414
415bool
416DynamicLoaderMacOSXDYLD::ReadAllImageInfosStructure ()
417{
418 Mutex::Locker locker(m_mutex);
Greg Clayton20d338f2010-11-18 05:57:03 +0000419
420 // the all image infos is already valid for this process stop ID
421 if (m_process->GetStopID() == m_dyld_all_image_infos_stop_id)
422 return true;
423
Chris Lattner24943d22010-06-08 16:52:24 +0000424 m_dyld_all_image_infos.Clear();
425 if (m_dyld_all_image_infos_addr != LLDB_INVALID_ADDRESS)
426 {
Greg Clayton20d338f2010-11-18 05:57:03 +0000427 ByteOrder byte_order = m_process->GetByteOrder();
428 uint32_t addr_size = 4;
429 if (m_dyld_all_image_infos_addr > UINT32_MAX)
430 addr_size = 8;
431
Chris Lattner24943d22010-06-08 16:52:24 +0000432 uint8_t buf[256];
Greg Clayton20d338f2010-11-18 05:57:03 +0000433 DataExtractor data (buf, sizeof(buf), byte_order, addr_size);
434 uint32_t offset = 0;
435
Jason Molenda1f3af542010-06-10 01:21:21 +0000436 const size_t count_v2 = sizeof (uint32_t) + // version
437 sizeof (uint32_t) + // infoArrayCount
438 addr_size + // infoArray
439 addr_size + // notification
440 addr_size + // processDetachedFromSharedRegion + libSystemInitialized + pad
441 addr_size; // dyldImageLoadAddress
442 const size_t count_v11 = count_v2 +
443 addr_size + // jitInfo
444 addr_size + // dyldVersion
445 addr_size + // errorMessage
446 addr_size + // terminationFlags
447 addr_size + // coreSymbolicationShmPage
448 addr_size + // systemOrderFlag
449 addr_size + // uuidArrayCount
450 addr_size + // uuidArray
451 addr_size + // dyldAllImageInfosAddress
452 addr_size + // initialImageCount
453 addr_size + // errorKind
454 addr_size + // errorClientOfDylibPath
455 addr_size + // errorTargetDylibPath
456 addr_size; // errorSymbol
457 assert (sizeof (buf) > count_v11);
458
459 int count;
Chris Lattner24943d22010-06-08 16:52:24 +0000460 Error error;
Jason Molenda1f3af542010-06-10 01:21:21 +0000461 if (m_process->ReadMemory (m_dyld_all_image_infos_addr, buf, 4, error) == 4)
462 {
Jason Molenda1f3af542010-06-10 01:21:21 +0000463 m_dyld_all_image_infos.version = data.GetU32(&offset);
Greg Clayton20d338f2010-11-18 05:57:03 +0000464 // If anything in the high byte is set, we probably got the byte
465 // order incorrect (the process might not have it set correctly
466 // yet due to attaching to a program without a specified file).
467 if (m_dyld_all_image_infos.version & 0xff000000)
468 {
469 // We have guessed the wrong byte order. Swap it and try
470 // reading the version again.
471 if (byte_order == eByteOrderLittle)
472 byte_order = eByteOrderBig;
473 else
474 byte_order = eByteOrderLittle;
475
476 data.SetByteOrder (byte_order);
477 offset = 0;
478 m_dyld_all_image_infos.version = data.GetU32(&offset);
479 }
Jason Molenda1f3af542010-06-10 01:21:21 +0000480 }
481 else
482 {
483 return false;
484 }
485
486 if (m_dyld_all_image_infos.version >= 11)
487 count = count_v11;
488 else
489 count = count_v2;
490
Chris Lattner24943d22010-06-08 16:52:24 +0000491 const size_t bytes_read = m_process->ReadMemory (m_dyld_all_image_infos_addr, buf, count, error);
492 if (bytes_read == count)
493 {
Greg Clayton20d338f2010-11-18 05:57:03 +0000494 offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000495 m_dyld_all_image_infos.version = data.GetU32(&offset);
496 m_dyld_all_image_infos.dylib_info_count = data.GetU32(&offset);
497 m_dyld_all_image_infos.dylib_info_addr = data.GetPointer(&offset);
498 m_dyld_all_image_infos.notification = data.GetPointer(&offset);
499 m_dyld_all_image_infos.processDetachedFromSharedRegion = data.GetU8(&offset);
Jason Molenda1f3af542010-06-10 01:21:21 +0000500 m_dyld_all_image_infos.libSystemInitialized = data.GetU8(&offset);
501 // Adjust for padding.
502 offset += addr_size - 2;
503 m_dyld_all_image_infos.dyldImageLoadAddress = data.GetPointer(&offset);
504 if (m_dyld_all_image_infos.version >= 11)
Chris Lattner24943d22010-06-08 16:52:24 +0000505 {
Jason Molenda1f3af542010-06-10 01:21:21 +0000506 offset += addr_size * 8;
507 uint64_t dyld_all_image_infos_addr = data.GetPointer(&offset);
508
509 // When we started, we were given the actual address of the all_image_infos
510 // struct (probably via TASK_DYLD_INFO) in memory - this address is stored in
511 // m_dyld_all_image_infos_addr and is the most accurate address we have.
512
513 // We read the dyld_all_image_infos struct from memory; it contains its own address.
514 // If the address in the struct does not match the actual address,
515 // the dyld we're looking at has been loaded at a different location (slid) from
516 // where it intended to load. The addresses in the dyld_all_image_infos struct
517 // are the original, non-slid addresses, and need to be adjusted. Most importantly
518 // the address of dyld and the notification address need to be adjusted.
519
520 if (dyld_all_image_infos_addr != m_dyld_all_image_infos_addr)
521 {
522 uint64_t image_infos_offset = dyld_all_image_infos_addr - m_dyld_all_image_infos.dyldImageLoadAddress;
523 uint64_t notification_offset = m_dyld_all_image_infos.notification - m_dyld_all_image_infos.dyldImageLoadAddress;
524 m_dyld_all_image_infos.dyldImageLoadAddress = m_dyld_all_image_infos_addr - image_infos_offset;
525 m_dyld_all_image_infos.notification = m_dyld_all_image_infos.dyldImageLoadAddress + notification_offset;
526 }
Chris Lattner24943d22010-06-08 16:52:24 +0000527 }
Greg Clayton20d338f2010-11-18 05:57:03 +0000528 m_dyld_all_image_infos_stop_id = m_process->GetStopID();
Chris Lattner24943d22010-06-08 16:52:24 +0000529 return true;
530 }
531 }
532 return false;
533}
534
535//----------------------------------------------------------------------
536// If we have found where the "_dyld_all_image_infos" lives in memory,
537// read the current info from it, and then update all image load
538// addresses (or lack thereof).
539//----------------------------------------------------------------------
540uint32_t
541DynamicLoaderMacOSXDYLD::UpdateAllImageInfos()
542{
Greg Claytone005f2c2010-11-06 01:53:30 +0000543 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
Chris Lattner24943d22010-06-08 16:52:24 +0000544 if (ReadAllImageInfosStructure ())
545 {
546 Mutex::Locker locker(m_mutex);
Greg Clayton20d338f2010-11-18 05:57:03 +0000547 if (m_process->GetStopID() == m_dyld_image_infos_stop_id)
548 m_dyld_image_infos.size();
549
Chris Lattner24943d22010-06-08 16:52:24 +0000550 uint32_t idx;
Chris Lattner24943d22010-06-08 16:52:24 +0000551 uint32_t i = 0;
552 DYLDImageInfo::collection old_dyld_all_image_infos;
553 old_dyld_all_image_infos.swap(m_dyld_image_infos);
554
555 // If we made it here, we are assuming that the all dylib info data should
556 // be valid, lets read the info array.
Greg Clayton20d338f2010-11-18 05:57:03 +0000557 const ByteOrder endian = m_dyld.GetByteOrder();
558 const uint32_t addr_size = m_dyld.GetAddressByteSize();
Chris Lattner24943d22010-06-08 16:52:24 +0000559
560 if (m_dyld_all_image_infos.dylib_info_count > 0)
561 {
562 if (m_dyld_all_image_infos.dylib_info_addr == 0)
563 {
564 // DYLD is updating the images right now...
565 }
566 else
567 {
568 m_dyld_image_infos.resize(m_dyld_all_image_infos.dylib_info_count);
569 const size_t count = m_dyld_image_infos.size() * 3 * addr_size;
570 DataBufferHeap info_data(count, 0);
571 Error error;
572 const size_t bytes_read = m_process->ReadMemory (m_dyld_all_image_infos.dylib_info_addr,
573 info_data.GetBytes(),
574 info_data.GetByteSize(),
575 error);
576 if (bytes_read == count)
577 {
578 uint32_t info_data_offset = 0;
579 DataExtractor info_data_ref(info_data.GetBytes(), info_data.GetByteSize(), endian, addr_size);
580 for (i = 0; info_data_ref.ValidOffset(info_data_offset); i++)
581 {
582 assert (i < m_dyld_image_infos.size());
583 m_dyld_image_infos[i].address = info_data_ref.GetPointer(&info_data_offset);
584 lldb::addr_t path_addr = info_data_ref.GetPointer(&info_data_offset);
585 m_dyld_image_infos[i].mod_date = info_data_ref.GetPointer(&info_data_offset);
586
587 char raw_path[PATH_MAX];
588 m_process->ReadMemory (path_addr, raw_path, sizeof(raw_path), error);
Greg Clayton537a7a82010-10-20 20:54:39 +0000589 m_dyld_image_infos[i].file_spec.SetFile(raw_path, true);
Chris Lattner24943d22010-06-08 16:52:24 +0000590 }
591 assert(i == m_dyld_all_image_infos.dylib_info_count);
592
593 UpdateAllImageInfosHeaderAndLoadCommands();
594 }
595 else
596 {
597 DEBUG_PRINTF( "unable to read all data for all_dylib_infos.");
598 m_dyld_image_infos.clear();
599 }
600 }
601 }
602 else
603 {
604 m_dyld_image_infos.clear();
605 }
606
607 // If our new list is smaller than our old list, we have unloaded
608 // some shared libraries
Greg Claytonab429022010-12-12 21:03:32 +0000609 if (m_dyld_image_infos.size() != old_dyld_all_image_infos.size())
Chris Lattner24943d22010-06-08 16:52:24 +0000610 {
611 ModuleList unloaded_module_list;
Greg Claytonab429022010-12-12 21:03:32 +0000612 if (old_dyld_all_image_infos.size() == 0)
Chris Lattner24943d22010-06-08 16:52:24 +0000613 {
Greg Claytonab429022010-12-12 21:03:32 +0000614 // This is the first time we are loading shared libraries,
615 // we need to make sure to trim anything that isn't in the
616 // m_dyld_image_infos out of the target module list since
617 // we might have shared libraries that got loaded from
618 // elsewhere due to DYLD_FRAMEWORK_PATH, or DYLD_LIBRARY_PATH
619 // environment variables...
620 ModuleList& images = m_process->GetTarget().GetImages();
621 const size_t num_images = images.GetSize();
622 for (idx = 0; idx < num_images; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +0000623 {
Greg Claytonab429022010-12-12 21:03:32 +0000624 ModuleSP module_sp (images.GetModuleAtIndex (idx));
625
626 if (GetImageInfo (module_sp->GetFileSpec(), module_sp->GetUUID()) == NULL)
627 unloaded_module_list.AppendIfNeeded (module_sp);
Chris Lattner24943d22010-06-08 16:52:24 +0000628 }
629 }
Greg Claytonab429022010-12-12 21:03:32 +0000630 else
Greg Clayton9d2993d2010-11-03 04:08:06 +0000631 {
Greg Claytonab429022010-12-12 21:03:32 +0000632 uint32_t old_idx;
633 for (idx = 0; idx < old_dyld_all_image_infos.size(); ++idx)
Greg Clayton9d2993d2010-11-03 04:08:06 +0000634 {
Greg Claytonab429022010-12-12 21:03:32 +0000635 for (old_idx = idx; old_idx < old_dyld_all_image_infos.size(); ++old_idx)
Greg Clayton9d2993d2010-11-03 04:08:06 +0000636 {
Greg Claytonab429022010-12-12 21:03:32 +0000637 if (m_dyld_image_infos[idx].file_spec == old_dyld_all_image_infos[old_idx].file_spec)
638 {
639 old_dyld_all_image_infos[old_idx].address = LLDB_INVALID_ADDRESS;
640 break;
641 }
642 }
643 }
644
645 if (log)
646 log->PutCString("Unloaded:");
647
648 for (old_idx = 0; old_idx < old_dyld_all_image_infos.size(); ++old_idx)
649 {
650 if (old_dyld_all_image_infos[old_idx].address != LLDB_INVALID_ADDRESS)
651 {
652 if (log)
653 old_dyld_all_image_infos[old_idx].PutToLog (log.get());
654 ModuleSP unload_image_module_sp(m_process->GetTarget().GetImages().FindFirstModuleForFileSpec (old_dyld_all_image_infos[old_idx].file_spec));
655 if (unload_image_module_sp.get())
656 {
657 if (UnloadImageLoadAddress (unload_image_module_sp.get(), old_dyld_all_image_infos[old_idx]))
658 unloaded_module_list.AppendIfNeeded (unload_image_module_sp);
659 }
Greg Clayton9d2993d2010-11-03 04:08:06 +0000660 }
661 }
662 }
663
Chris Lattner24943d22010-06-08 16:52:24 +0000664 if (unloaded_module_list.GetSize() > 0)
665 m_process->GetTarget().ModulesDidUnload (unloaded_module_list);
666 }
Greg Clayton9d2993d2010-11-03 04:08:06 +0000667 else
668 {
669 if (log)
Greg Claytone005f2c2010-11-06 01:53:30 +0000670 PutToLog(log.get());
Greg Clayton9d2993d2010-11-03 04:08:06 +0000671 }
Greg Clayton20d338f2010-11-18 05:57:03 +0000672 m_dyld_image_infos_stop_id = m_process->GetStopID();
Chris Lattner24943d22010-06-08 16:52:24 +0000673 }
674 else
675 {
676 m_dyld_image_infos.clear();
677 }
678
679 const uint32_t num_dylibs = m_dyld_image_infos.size();
680 if (num_dylibs > 0)
681 {
682 ModuleList loaded_module_list;
683 for (uint32_t idx = 0; idx<num_dylibs; ++idx)
684 {
Greg Claytoncf015052010-06-11 03:25:34 +0000685 ArchSpec arch_spec(eArchTypeMachO, m_dyld_image_infos[idx].header.cputype, m_dyld_image_infos[idx].header.cpusubtype);
Chris Lattner24943d22010-06-08 16:52:24 +0000686 ModuleSP image_module_sp(m_process->GetTarget().GetImages().FindFirstModuleForFileSpec (m_dyld_image_infos[idx].file_spec));
687 if (image_module_sp.get() == NULL || image_module_sp->GetArchitecture() != arch_spec)
688 {
689 image_module_sp = m_process->GetTarget().GetSharedModule (m_dyld_image_infos[idx].file_spec,
690 arch_spec,
691 &m_dyld_image_infos[idx].uuid);
692 }
693
694 if (image_module_sp)
695 {
Greg Clayton236c1c72010-09-07 23:40:05 +0000696 if (m_dyld_image_infos[idx].header.filetype == HeaderFileTypeDynamicLinkEditor)
697 image_module_sp->SetIsDynamicLinkEditor (true);
698
Chris Lattner24943d22010-06-08 16:52:24 +0000699 ObjectFile *objfile = image_module_sp->GetObjectFile ();
700 if (objfile)
701 {
702 SectionList *sections = objfile->GetSectionList();
703 if (sections)
704 {
705 ConstString commpage_dbstr("__commpage");
706 Section *commpage_section = sections->FindSectionByName(commpage_dbstr).get();
707 if (commpage_section)
708 {
709 FileSpec objfile_file_spec(objfile->GetFileSpec());
710 ModuleSP commpage_image_module_sp(m_process->GetTarget().GetImages().FindFirstModuleForFileSpec (objfile_file_spec, &commpage_dbstr));
711 if (commpage_image_module_sp.get() == NULL)
712 {
713 commpage_image_module_sp = m_process->GetTarget().GetSharedModule (m_dyld_image_infos[idx].file_spec,
714 arch_spec,
715 &m_dyld_image_infos[idx].uuid,
716 &commpage_dbstr,
717 objfile->GetOffset() + commpage_section->GetOffset());
718 UpdateCommPageLoadAddress(commpage_image_module_sp.get());
719 }
720 }
721 }
722 }
723
724 // UpdateImageLoadAddress will return true if any segments
725 // change load address. We need to check this so we don't
726 // mention that all loaded shared libraries are newly loaded
727 // each time we hit out dyld breakpoint since dyld will list all
728 // shared libraries each time.
729 if (UpdateImageLoadAddress (image_module_sp.get(), m_dyld_image_infos[idx]))
730 {
Greg Claytonab429022010-12-12 21:03:32 +0000731 loaded_module_list.AppendIfNeeded (image_module_sp);
Chris Lattner24943d22010-06-08 16:52:24 +0000732 }
733 }
734 }
Chris Lattner24943d22010-06-08 16:52:24 +0000735 if (loaded_module_list.GetSize() > 0)
736 {
737 // FIXME: This should really be in the Runtime handlers class, which should get
738 // called by the target's ModulesDidLoad, but we're doing it all locally for now
739 // to save time.
740 // Also, I'm assuming there can be only one libobjc dylib loaded...
741
Jim Inghamb66cd072010-09-28 01:25:32 +0000742 ObjCLanguageRuntime *objc_runtime = m_process->GetObjCLanguageRuntime();
743 if (objc_runtime != NULL && !objc_runtime->HasReadObjCLibrary())
Chris Lattner24943d22010-06-08 16:52:24 +0000744 {
745 size_t num_modules = loaded_module_list.GetSize();
746 for (int i = 0; i < num_modules; i++)
747 {
Jim Inghamb66cd072010-09-28 01:25:32 +0000748 if (objc_runtime->IsModuleObjCLibrary (loaded_module_list.GetModuleAtIndex (i)))
Chris Lattner24943d22010-06-08 16:52:24 +0000749 {
Jim Inghamb66cd072010-09-28 01:25:32 +0000750 objc_runtime->ReadObjCLibrary (loaded_module_list.GetModuleAtIndex (i));
Chris Lattner24943d22010-06-08 16:52:24 +0000751 break;
752 }
753 }
754 }
755 m_process->GetTarget().ModulesDidLoad (loaded_module_list);
756 }
757 }
758 return m_dyld_image_infos.size();
759}
760
761//----------------------------------------------------------------------
762// Read a mach_header at ADDR into HEADER, and also fill in the load
763// command data into LOAD_COMMAND_DATA if it is non-NULL.
764//
765// Returns true if we succeed, false if we fail for any reason.
766//----------------------------------------------------------------------
767bool
Greg Clayton1674b122010-07-21 22:12:05 +0000768DynamicLoaderMacOSXDYLD::ReadMachHeader (lldb::addr_t addr, mach_header *header, DataExtractor *load_command_data)
Chris Lattner24943d22010-06-08 16:52:24 +0000769{
Greg Clayton1674b122010-07-21 22:12:05 +0000770 DataBufferHeap header_bytes(sizeof(mach_header), 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000771 Error error;
772 size_t bytes_read = m_process->ReadMemory (addr,
773 header_bytes.GetBytes(),
774 header_bytes.GetByteSize(),
775 error);
Greg Clayton1674b122010-07-21 22:12:05 +0000776 if (bytes_read == sizeof(mach_header))
Chris Lattner24943d22010-06-08 16:52:24 +0000777 {
778 uint32_t offset = 0;
779 ::memset (header, 0, sizeof(header));
780
781 // Get the magic byte unswapped so we can figure out what we are dealing with
782 DataExtractor data(header_bytes.GetBytes(), header_bytes.GetByteSize(), eByteOrderHost, 4);
783 header->magic = data.GetU32(&offset);
784 lldb::addr_t load_cmd_addr = addr;
785 data.SetByteOrder(DynamicLoaderMacOSXDYLD::GetByteOrderFromMagic(header->magic));
786 switch (header->magic)
787 {
Greg Clayton1674b122010-07-21 22:12:05 +0000788 case llvm::MachO::HeaderMagic32:
789 case llvm::MachO::HeaderMagic32Swapped:
Chris Lattner24943d22010-06-08 16:52:24 +0000790 data.SetAddressByteSize(4);
Greg Clayton1674b122010-07-21 22:12:05 +0000791 load_cmd_addr += sizeof(mach_header);
Chris Lattner24943d22010-06-08 16:52:24 +0000792 break;
793
Greg Clayton1674b122010-07-21 22:12:05 +0000794 case llvm::MachO::HeaderMagic64:
795 case llvm::MachO::HeaderMagic64Swapped:
Chris Lattner24943d22010-06-08 16:52:24 +0000796 data.SetAddressByteSize(8);
Greg Clayton1674b122010-07-21 22:12:05 +0000797 load_cmd_addr += sizeof(mach_header_64);
Chris Lattner24943d22010-06-08 16:52:24 +0000798 break;
799
800 default:
801 return false;
802 }
803
804 // Read the rest of dyld's mach header
Greg Clayton1674b122010-07-21 22:12:05 +0000805 if (data.GetU32(&offset, &header->cputype, (sizeof(mach_header)/sizeof(uint32_t)) - 1))
Chris Lattner24943d22010-06-08 16:52:24 +0000806 {
807 if (load_command_data == NULL)
808 return true; // We were able to read the mach_header and weren't asked to read the load command bytes
809
810 DataBufferSP load_cmd_data_sp(new DataBufferHeap(header->sizeofcmds, 0));
811
812 size_t load_cmd_bytes_read = m_process->ReadMemory (load_cmd_addr,
813 load_cmd_data_sp->GetBytes(),
814 load_cmd_data_sp->GetByteSize(),
815 error);
816
817 if (load_cmd_bytes_read == header->sizeofcmds)
818 {
819 // Set the load command data and also set the correct endian
820 // swap settings and the correct address size
821 load_command_data->SetData(load_cmd_data_sp, 0, header->sizeofcmds);
822 load_command_data->SetByteOrder(data.GetByteOrder());
823 load_command_data->SetAddressByteSize(data.GetAddressByteSize());
824 return true; // We successfully read the mach_header and the load command data
825 }
826
827 return false; // We weren't able to read the load command data
828 }
829 }
830 return false; // We failed the read the mach_header
831}
832
833
834//----------------------------------------------------------------------
835// Parse the load commands for an image
836//----------------------------------------------------------------------
837uint32_t
838DynamicLoaderMacOSXDYLD::ParseLoadCommands (const DataExtractor& data, struct DYLDImageInfo& dylib_info, FileSpec *lc_id_dylinker)
839{
840 uint32_t offset = 0;
841 uint32_t cmd_idx;
842 Segment segment;
843 dylib_info.Clear (true);
844
845 for (cmd_idx = 0; cmd_idx < dylib_info.header.ncmds; cmd_idx++)
846 {
847 // Clear out any load command specific data from DYLIB_INFO since
848 // we are about to read it.
849
Greg Clayton1674b122010-07-21 22:12:05 +0000850 if (data.ValidOffsetForDataOfSize (offset, sizeof(load_command)))
Chris Lattner24943d22010-06-08 16:52:24 +0000851 {
Greg Clayton1674b122010-07-21 22:12:05 +0000852 load_command load_cmd;
Chris Lattner24943d22010-06-08 16:52:24 +0000853 uint32_t load_cmd_offset = offset;
854 load_cmd.cmd = data.GetU32 (&offset);
855 load_cmd.cmdsize = data.GetU32 (&offset);
856 switch (load_cmd.cmd)
857 {
Greg Clayton1674b122010-07-21 22:12:05 +0000858 case LoadCommandSegment32:
Chris Lattner24943d22010-06-08 16:52:24 +0000859 {
860 segment.name.SetTrimmedCStringWithLength ((const char *)data.GetData(&offset, 16), 16);
861 segment.addr = data.GetU32 (&offset);
862 segment.size = data.GetU32 (&offset);
863 dylib_info.segments.push_back (segment);
864 }
865 break;
866
Greg Clayton1674b122010-07-21 22:12:05 +0000867 case LoadCommandSegment64:
Chris Lattner24943d22010-06-08 16:52:24 +0000868 {
869 segment.name.SetTrimmedCStringWithLength ((const char *)data.GetData(&offset, 16), 16);
870 segment.addr = data.GetU64 (&offset);
871 segment.size = data.GetU64 (&offset);
872 dylib_info.segments.push_back (segment);
873 }
874 break;
875
Greg Clayton1674b122010-07-21 22:12:05 +0000876 case LoadCommandDynamicLinkerIdent:
Chris Lattner24943d22010-06-08 16:52:24 +0000877 if (lc_id_dylinker)
878 {
879 uint32_t name_offset = load_cmd_offset + data.GetU32 (&offset);
880 const char *path = data.PeekCStr (name_offset);
Greg Clayton537a7a82010-10-20 20:54:39 +0000881 lc_id_dylinker->SetFile (path, true);
Chris Lattner24943d22010-06-08 16:52:24 +0000882 }
883 break;
884
Greg Clayton1674b122010-07-21 22:12:05 +0000885 case LoadCommandUUID:
Chris Lattner24943d22010-06-08 16:52:24 +0000886 dylib_info.uuid.SetBytes(data.GetData (&offset, 16));
887 break;
888
889 default:
890 break;
891 }
892 // Set offset to be the beginning of the next load command.
893 offset = load_cmd_offset + load_cmd.cmdsize;
894 }
895 }
896 return cmd_idx;
897}
898
899//----------------------------------------------------------------------
900// Read the mach_header and load commands for each image that the
901// _dyld_all_image_infos structure points to and cache the results.
902//----------------------------------------------------------------------
903void
904DynamicLoaderMacOSXDYLD::UpdateAllImageInfosHeaderAndLoadCommands()
905{
906 uint32_t exe_idx = UINT32_MAX;
907 // Read any UUID values that we can get
908 for (uint32_t i = 0; i < m_dyld_all_image_infos.dylib_info_count; i++)
909 {
910 if (!m_dyld_image_infos[i].UUIDValid())
911 {
912 DataExtractor data; // Load command data
913 if (!ReadMachHeader (m_dyld_image_infos[i].address, &m_dyld_image_infos[i].header, &data))
914 continue;
915
916 ParseLoadCommands (data, m_dyld_image_infos[i], NULL);
917
Greg Clayton1674b122010-07-21 22:12:05 +0000918 if (m_dyld_image_infos[i].header.filetype == HeaderFileTypeExecutable)
Chris Lattner24943d22010-06-08 16:52:24 +0000919 exe_idx = i;
920 }
921 }
922
923 if (exe_idx < m_dyld_image_infos.size())
924 {
925 bool set_executable = false;
Greg Claytoncf015052010-06-11 03:25:34 +0000926 ArchSpec dyld_exe_arch_spec(eArchTypeMachO, m_dyld_image_infos[exe_idx].header.cputype, m_dyld_image_infos[exe_idx].header.cpusubtype);
Chris Lattner24943d22010-06-08 16:52:24 +0000927 ModuleSP exe_module_sp(m_process->GetTarget().GetExecutableModule());
928 if (exe_module_sp.get())
929 {
930 if (exe_module_sp->GetFileSpec() != m_dyld_image_infos[exe_idx].file_spec ||
931 exe_module_sp->GetArchitecture() != dyld_exe_arch_spec)
932 set_executable = true;
933 }
934 else
935 set_executable = true;
936
937 if (set_executable)
938 {
939 exe_module_sp = m_process->GetTarget().GetSharedModule (m_dyld_image_infos[exe_idx].file_spec,
940 dyld_exe_arch_spec,
941 &m_dyld_image_infos[exe_idx].uuid);
942 if (exe_module_sp.get())
943 {
944 // If we found the file where it purported to be, then it should
945 // be safe to load dependent images.
946 bool get_dependent_images = exe_module_sp->GetFileSpec() == m_dyld_image_infos[exe_idx].file_spec;
947
948 m_process->GetTarget().SetExecutableModule (exe_module_sp, get_dependent_images);
949 }
950 }
951 }
952}
953
954//----------------------------------------------------------------------
955// Dump a Segment to the file handle provided.
956//----------------------------------------------------------------------
957void
958DynamicLoaderMacOSXDYLD::Segment::PutToLog (Log *log, lldb::addr_t slide) const
959{
960 if (log)
961 log->Printf("\t\t%16s [0x%16.16llx - 0x%16.16llx)", name.AsCString(""), addr + slide, addr + slide + size);
962}
963
964const DynamicLoaderMacOSXDYLD::Segment *
965DynamicLoaderMacOSXDYLD::DYLDImageInfo::FindSegment (const ConstString &name) const
966{
967 const size_t num_segments = segments.size();
968 for (size_t i=0; i<num_segments; ++i)
969 {
970 if (segments[i].name == name)
971 return &segments[i];
972 }
973 return NULL;
974}
975
976
977//----------------------------------------------------------------------
978// Dump an image info structure to the file handle provided.
979//----------------------------------------------------------------------
980void
981DynamicLoaderMacOSXDYLD::DYLDImageInfo::PutToLog (Log *log) const
982{
983 if (log == NULL)
984 return;
985 uint8_t *u = (uint8_t *)uuid.GetBytes();
986
987 if (address == LLDB_INVALID_ADDRESS)
988 {
989 if (u)
990 {
991 log->Printf("\t modtime=0x%8.8llx 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 path='%s/%s' (UNLOADED)",
992 mod_date,
993 u[ 0], u[ 1], u[ 2], u[ 3],
994 u[ 4], u[ 5], u[ 6], u[ 7],
995 u[ 8], u[ 9], u[10], u[11],
996 u[12], u[13], u[14], u[15],
997 file_spec.GetDirectory().AsCString(),
998 file_spec.GetFilename().AsCString());
999 }
1000 else
1001 log->Printf("\t modtime=0x%8.8llx path='%s/%s' (UNLOADED)",
1002 mod_date,
1003 file_spec.GetDirectory().AsCString(),
1004 file_spec.GetFilename().AsCString());
1005 }
1006 else
1007 {
1008 if (u)
1009 {
1010 log->Printf("\taddress=0x%16.16llx modtime=0x%8.8llx 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 path='%s/%s'",
1011 address,
1012 mod_date,
1013 u[ 0], u[ 1], u[ 2], u[ 3],
1014 u[ 4], u[ 5], u[ 6], u[ 7],
1015 u[ 8], u[ 9], u[10], u[11],
1016 u[12], u[13], u[14], u[15],
1017 file_spec.GetDirectory().AsCString(),
1018 file_spec.GetFilename().AsCString());
1019 }
1020 else
1021 {
1022 log->Printf("\taddress=0x%16.16llx modtime=0x%8.8llx path='%s/%s'",
1023 address,
1024 mod_date,
1025 file_spec.GetDirectory().AsCString(),
1026 file_spec.GetFilename().AsCString());
1027
1028 }
1029 for (uint32_t i=0; i<segments.size(); ++i)
1030 segments[i].PutToLog(log, slide);
1031 }
1032}
1033
1034//----------------------------------------------------------------------
1035// Dump the _dyld_all_image_infos members and all current image infos
1036// that we have parsed to the file handle provided.
1037//----------------------------------------------------------------------
1038void
1039DynamicLoaderMacOSXDYLD::PutToLog(Log *log) const
1040{
1041 if (log == NULL)
1042 return;
1043
1044 Mutex::Locker locker(m_mutex);
1045 log->Printf("dyld_all_image_infos = { version=%d, count=%d, addr=0x%8.8llx, notify=0x%8.8llx }",
1046 m_dyld_all_image_infos.version,
1047 m_dyld_all_image_infos.dylib_info_count,
1048 (uint64_t)m_dyld_all_image_infos.dylib_info_addr,
1049 (uint64_t)m_dyld_all_image_infos.notification);
1050 size_t i;
1051 const size_t count = m_dyld_image_infos.size();
1052 if (count > 0)
1053 {
Greg Clayton9d2993d2010-11-03 04:08:06 +00001054 log->PutCString("Loaded:");
Chris Lattner24943d22010-06-08 16:52:24 +00001055 for (i = 0; i<count; i++)
1056 m_dyld_image_infos[i].PutToLog(log);
1057 }
1058}
1059
Chris Lattner24943d22010-06-08 16:52:24 +00001060void
1061DynamicLoaderMacOSXDYLD::PrivateInitialize(Process *process)
1062{
1063 DEBUG_PRINTF("DynamicLoaderMacOSXDYLD::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState()));
1064 Clear(true);
1065 m_process = process;
Greg Clayton58e844b2010-12-08 05:08:21 +00001066 m_process->GetTarget().GetSectionLoadList().Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001067}
1068
1069bool
1070DynamicLoaderMacOSXDYLD::SetNotificationBreakpoint ()
1071{
1072 DEBUG_PRINTF("DynamicLoaderMacOSXDYLD::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState()));
1073 if (m_break_id == LLDB_INVALID_BREAK_ID)
1074 {
1075 if (m_dyld_all_image_infos.notification != LLDB_INVALID_ADDRESS)
1076 {
1077 Address so_addr;
1078 // Set the notification breakpoint and install a breakpoint
1079 // callback function that will get called each time the
1080 // breakpoint gets hit. We will use this to track when shared
1081 // libraries get loaded/unloaded.
1082
Greg Claytoneea26402010-09-14 23:36:40 +00001083 if (m_process->GetTarget().GetSectionLoadList().ResolveLoadAddress(m_dyld_all_image_infos.notification, so_addr))
Chris Lattner24943d22010-06-08 16:52:24 +00001084 {
1085 Breakpoint *dyld_break = m_process->GetTarget().CreateBreakpoint (so_addr, true).get();
1086 dyld_break->SetCallback (DynamicLoaderMacOSXDYLD::NotifyBreakpointHit, this, true);
1087 m_break_id = dyld_break->GetID();
1088 }
1089 }
1090 }
1091 return m_break_id != LLDB_INVALID_BREAK_ID;
1092}
1093
Jim Ingham7508e732010-08-09 23:31:02 +00001094//----------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00001095// Member function that gets called when the process state changes.
1096//----------------------------------------------------------------------
1097void
1098DynamicLoaderMacOSXDYLD::PrivateProcessStateChanged (Process *process, StateType state)
1099{
1100 DEBUG_PRINTF("DynamicLoaderMacOSXDYLD::%s(%s)\n", __FUNCTION__, StateAsCString(state));
1101 switch (state)
1102 {
1103 case eStateAttaching:
1104 case eStateLaunching:
1105 case eStateInvalid:
1106 case eStateUnloaded:
1107 case eStateExited:
1108 case eStateDetached:
1109 Clear(false);
1110 break;
1111
1112 case eStateStopped:
1113 // Keep trying find dyld and set our notification breakpoint each time
1114 // we stop until we succeed
1115 if (!DidSetNotificationBreakpoint () && m_process->IsAlive())
1116 {
1117 if (NeedToLocateDYLD ())
1118 LocateDYLD ();
1119
1120 SetNotificationBreakpoint ();
1121 }
1122 break;
1123
1124 case eStateRunning:
1125 case eStateStepping:
1126 case eStateCrashed:
1127 case eStateSuspended:
1128 break;
1129
1130 default:
1131 break;
1132 }
1133}
1134
1135ThreadPlanSP
1136DynamicLoaderMacOSXDYLD::GetStepThroughTrampolinePlan (Thread &thread, bool stop_others)
1137{
1138 ThreadPlanSP thread_plan_sp;
1139 StackFrame *current_frame = thread.GetStackFrameAtIndex(0).get();
1140 const SymbolContext &current_context = current_frame->GetSymbolContext(eSymbolContextSymbol);
1141 Symbol *current_symbol = current_context.symbol;
Greg Claytone005f2c2010-11-06 01:53:30 +00001142 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Chris Lattner24943d22010-06-08 16:52:24 +00001143
1144 if (current_symbol != NULL)
1145 {
1146 if (current_symbol->IsTrampoline())
1147 {
Jim Ingham17454cf2010-09-14 22:03:00 +00001148 const ConstString &trampoline_name = current_symbol->GetMangled().GetName(Mangled::ePreferMangled);
1149
Chris Lattner24943d22010-06-08 16:52:24 +00001150 if (trampoline_name)
1151 {
1152 SymbolContextList target_symbols;
1153 ModuleList &images = thread.GetProcess().GetTarget().GetImages();
1154 images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeCode, target_symbols);
1155 // FIXME - Make the Run to Address take multiple addresses, and
1156 // run to any of them.
Jim Ingham17454cf2010-09-14 22:03:00 +00001157 uint32_t num_symbols = target_symbols.GetSize();
1158 if (num_symbols == 1)
Chris Lattner24943d22010-06-08 16:52:24 +00001159 {
1160 SymbolContext context;
1161 AddressRange addr_range;
1162 if (target_symbols.GetContextAtIndex(0, context))
1163 {
1164 context.GetAddressRange (eSymbolContextEverything, addr_range);
1165 thread_plan_sp.reset (new ThreadPlanRunToAddress (thread, addr_range.GetBaseAddress(), stop_others));
1166 }
Jim Ingham17454cf2010-09-14 22:03:00 +00001167 else
Chris Lattner24943d22010-06-08 16:52:24 +00001168 {
Jim Ingham17454cf2010-09-14 22:03:00 +00001169 if (log)
1170 log->Printf ("Couldn't resolve the symbol context.");
1171 }
1172 }
1173 else if (num_symbols > 1)
1174 {
1175 std::vector<lldb::addr_t> addresses;
1176 addresses.resize (num_symbols);
1177 for (uint32_t i = 0; i < num_symbols; i++)
1178 {
1179 SymbolContext context;
1180 AddressRange addr_range;
1181 if (target_symbols.GetContextAtIndex(i, context))
1182 {
1183 context.GetAddressRange (eSymbolContextEverything, addr_range);
Greg Claytoneea26402010-09-14 23:36:40 +00001184 lldb::addr_t load_addr = addr_range.GetBaseAddress().GetLoadAddress(&thread.GetProcess().GetTarget());
Jim Ingham17454cf2010-09-14 22:03:00 +00001185 addresses[i] = load_addr;
1186 }
1187 }
1188 if (addresses.size() > 0)
1189 thread_plan_sp.reset (new ThreadPlanRunToAddress (thread, addresses, stop_others));
1190 else
1191 {
1192 if (log)
1193 log->Printf ("Couldn't resolve the symbol contexts.");
Chris Lattner24943d22010-06-08 16:52:24 +00001194 }
1195 }
1196 else
1197 {
Chris Lattner24943d22010-06-08 16:52:24 +00001198 if (log)
1199 {
1200 log->Printf ("Could not find symbol for trampoline target: \"%s\"", trampoline_name.AsCString());
1201 }
1202 }
1203 }
1204 }
1205 }
Jim Ingham17454cf2010-09-14 22:03:00 +00001206 else
1207 {
1208 if (log)
1209 log->Printf ("Could not find symbol for step through.");
1210 }
Chris Lattner24943d22010-06-08 16:52:24 +00001211
Chris Lattner24943d22010-06-08 16:52:24 +00001212 return thread_plan_sp;
1213}
1214
Greg Clayton0baa3942010-11-04 01:54:29 +00001215Error
1216DynamicLoaderMacOSXDYLD::CanLoadImage ()
1217{
1218 Error error;
1219 // In order for us to tell if we can load a shared library we verify that
1220 // the dylib_info_addr isn't zero (which means no shared libraries have
1221 // been set yet, or dyld is currently mucking with the shared library list).
1222 if (ReadAllImageInfosStructure ())
1223 {
1224 // TODO: also check the _dyld_global_lock_held variable in libSystem.B.dylib?
1225 // TODO: check the malloc lock?
1226 // TODO: check the objective C lock?
1227 if (m_dyld_all_image_infos.dylib_info_addr != 0)
1228 return error; // Success
1229 }
1230
1231 error.SetErrorString("unsafe to load or unload shared libraries");
1232 return error;
1233}
1234
Chris Lattner24943d22010-06-08 16:52:24 +00001235void
1236DynamicLoaderMacOSXDYLD::Initialize()
1237{
1238 PluginManager::RegisterPlugin (GetPluginNameStatic(),
1239 GetPluginDescriptionStatic(),
1240 CreateInstance);
1241}
1242
1243void
1244DynamicLoaderMacOSXDYLD::Terminate()
1245{
1246 PluginManager::UnregisterPlugin (CreateInstance);
1247}
1248
1249
1250const char *
1251DynamicLoaderMacOSXDYLD::GetPluginNameStatic()
1252{
1253 return "dynamic-loader.macosx-dyld";
1254}
1255
1256const char *
1257DynamicLoaderMacOSXDYLD::GetPluginDescriptionStatic()
1258{
1259 return "Dynamic loader plug-in that watches for shared library loads/unloads in MacOSX user processes.";
1260}
1261
1262
1263//------------------------------------------------------------------
1264// PluginInterface protocol
1265//------------------------------------------------------------------
1266const char *
1267DynamicLoaderMacOSXDYLD::GetPluginName()
1268{
1269 return "DynamicLoaderMacOSXDYLD";
1270}
1271
1272const char *
1273DynamicLoaderMacOSXDYLD::GetShortPluginName()
1274{
1275 return GetPluginNameStatic();
1276}
1277
1278uint32_t
1279DynamicLoaderMacOSXDYLD::GetPluginVersion()
1280{
1281 return 1;
1282}
1283
1284void
1285DynamicLoaderMacOSXDYLD::GetPluginCommandHelp (const char *command, Stream *strm)
1286{
1287}
1288
1289Error
1290DynamicLoaderMacOSXDYLD::ExecutePluginCommand (Args &command, Stream *strm)
1291{
1292 Error error;
1293 error.SetErrorString("No plug-in command are currently supported.");
1294 return error;
1295}
1296
1297Log *
1298DynamicLoaderMacOSXDYLD::EnablePluginLogging (Stream *strm, Args &command)
1299{
1300 return NULL;
1301}
1302
1303