blob: fea069e5fc387323b706d725967ed748eb1c91f1 [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"
18#include "lldb/Target/RegisterContext.h"
19#include "lldb/Target/Target.h"
20#include "lldb/Target/Thread.h"
21#include "lldb/Target/ThreadPlanRunToAddress.h"
22#include "lldb/Target/StackFrame.h"
23
24#include "DynamicLoaderMacOSXDYLD.h"
25#include "DynamicLoaderMacOSXDYLDLog.h"
26
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
43//----------------------------------------------------------------------
44// Create an instance of this class. This function is filled into
45// the plugin info class that gets handed out by the plugin factory and
46// allows the lldb to instantiate an instance of this class.
47//----------------------------------------------------------------------
48DynamicLoader *
49DynamicLoaderMacOSXDYLD::CreateInstance (Process* process)
50{
51 return new DynamicLoaderMacOSXDYLD (process);
52}
53
54//----------------------------------------------------------------------
55// Constructor
56//----------------------------------------------------------------------
57DynamicLoaderMacOSXDYLD::DynamicLoaderMacOSXDYLD (Process* process) :
58 DynamicLoader(process),
59 m_dyld(),
60 m_dyld_all_image_infos_addr(LLDB_INVALID_ADDRESS),
61 m_dyld_all_image_infos(),
62 m_break_id(LLDB_INVALID_BREAK_ID),
63 m_dyld_image_infos(),
64 m_mutex(Mutex::eMutexTypeRecursive),
65 m_objc_trampoline_handler_ap(NULL)
66{
67}
68
69//----------------------------------------------------------------------
70// Destructor
71//----------------------------------------------------------------------
72DynamicLoaderMacOSXDYLD::~DynamicLoaderMacOSXDYLD()
73{
74 Clear(true);
75}
76
77//------------------------------------------------------------------
78/// Called after attaching a process.
79///
80/// Allow DynamicLoader plug-ins to execute some code after
81/// attaching to a process.
82//------------------------------------------------------------------
83void
84DynamicLoaderMacOSXDYLD::DidAttach ()
85{
86 PrivateInitialize(m_process);
87 if (NeedToLocateDYLD ())
88 LocateDYLD ();
89 SetNotificationBreakpoint ();
90 UpdateAllImageInfos();
91}
92
93//------------------------------------------------------------------
94/// Called after attaching a process.
95///
96/// Allow DynamicLoader plug-ins to execute some code after
97/// attaching to a process.
98//------------------------------------------------------------------
99void
100DynamicLoaderMacOSXDYLD::DidLaunch ()
101{
102 PrivateInitialize(m_process);
103 if (NeedToLocateDYLD ())
104 LocateDYLD ();
105 SetNotificationBreakpoint ();
106 UpdateAllImageInfos();
107}
108
109
110//----------------------------------------------------------------------
111// Clear out the state of this class.
112//----------------------------------------------------------------------
113void
114DynamicLoaderMacOSXDYLD::Clear (bool clear_process)
115{
116 Mutex::Locker locker(m_mutex);
117
118 if (m_process->IsAlive() && LLDB_BREAK_ID_IS_VALID(m_break_id))
119 m_process->ClearBreakpointSiteByID(m_break_id);
120
121 if (clear_process)
122 m_process = NULL;
123 m_dyld.Clear(false);
124 m_dyld_all_image_infos_addr = LLDB_INVALID_ADDRESS;
125 m_dyld_all_image_infos.Clear();
126 m_break_id = LLDB_INVALID_BREAK_ID;
127 m_dyld_image_infos.clear();
128}
129
130//----------------------------------------------------------------------
131// Check if we have found DYLD yet
132//----------------------------------------------------------------------
133bool
134DynamicLoaderMacOSXDYLD::DidSetNotificationBreakpoint() const
135{
136 return LLDB_BREAK_ID_IS_VALID (m_break_id);
137}
138
139//----------------------------------------------------------------------
140// Try and figure out where dyld is by first asking the Process
141// if it knows (which currently calls down in the the lldb::Process
142// to get the DYLD info (available on SnowLeopard only). If that fails,
143// then check in the default addresses.
144//----------------------------------------------------------------------
145bool
146DynamicLoaderMacOSXDYLD::LocateDYLD()
147{
148 if (m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS)
149 m_dyld_all_image_infos_addr = m_process->GetImageInfoAddress ();
150
151 if (m_dyld_all_image_infos_addr != LLDB_INVALID_ADDRESS)
152 {
153 if (ReadAllImageInfosStructure ())
154 {
155 if (m_dyld_all_image_infos.dyldImageLoadAddress != LLDB_INVALID_ADDRESS)
156 return ReadDYLDInfoFromMemoryAndSetNotificationCallback (m_dyld_all_image_infos.dyldImageLoadAddress);
157 else
158 return ReadDYLDInfoFromMemoryAndSetNotificationCallback (m_dyld_all_image_infos_addr & 0xfffffffffff00000ull);
159 }
160 }
161
162 // Check some default values
163 Module *executable = m_process->GetTarget().GetExecutableModule().get();
164
165 if (executable)
166 {
167 if (executable->GetArchitecture().GetAddressByteSize() == 8)
168 {
169 return ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x7fff5fc00000ull);
170 }
171#if defined (__arm__)
172 else
173 {
174 ArchSpec arm_arch("arm");
175 if (arm_arch == executable->Arch())
176 return ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x2fe00000);
177 }
178#endif
179 return ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x8fe00000);
180 }
181 return false;
182}
183
184//----------------------------------------------------------------------
185// Assume that dyld is in memory at ADDR and try to parse it's load
186// commands
187//----------------------------------------------------------------------
188bool
189DynamicLoaderMacOSXDYLD::ReadDYLDInfoFromMemoryAndSetNotificationCallback(lldb::addr_t addr)
190{
191 DataExtractor data; // Load command data
192 if (ReadMachHeader (addr, &m_dyld.header, &data))
193 {
Greg Clayton1674b122010-07-21 22:12:05 +0000194 if (m_dyld.header.filetype == HeaderFileTypeDynamicLinkEditor)
Chris Lattner24943d22010-06-08 16:52:24 +0000195 {
196 m_dyld.address = addr;
197 ModuleSP dyld_module_sp;
198 if (ParseLoadCommands (data, m_dyld, &m_dyld.file_spec))
199 {
200 if (m_dyld.file_spec)
201 {
Greg Claytoncf015052010-06-11 03:25:34 +0000202 ArchSpec dyld_arch(eArchTypeMachO, m_dyld.header.cputype, m_dyld.header.cpusubtype);
Chris Lattner24943d22010-06-08 16:52:24 +0000203 dyld_module_sp = m_process->GetTarget().GetImages().FindFirstModuleForFileSpec (m_dyld.file_spec);
204
205 if (dyld_module_sp.get() == NULL || dyld_module_sp->GetArchitecture() != dyld_arch)
206 {
207 dyld_module_sp = m_process->GetTarget().GetSharedModule (m_dyld.file_spec,
208 dyld_arch,
209 &m_dyld.uuid);
210 }
211
212 UpdateImageLoadAddress(dyld_module_sp.get(), m_dyld);
213 }
214 }
215
216 if (m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS && dyld_module_sp.get())
217 {
218 static ConstString g_dyld_all_image_infos ("dyld_all_image_infos");
219 const Symbol *symbol = dyld_module_sp->FindFirstSymbolWithNameAndType (g_dyld_all_image_infos, eSymbolTypeData);
220 if (symbol)
221 m_dyld_all_image_infos_addr = symbol->GetValue().GetLoadAddress(m_process);
222 }
223
224 // Update all image infos
225 UpdateAllImageInfos();
226
227 // If we didn't have an executable before, but now we do, then the
228 // dyld module shared pointer might be unique and we may need to add
229 // it again (since Target::SetExecutableModule() will clear the
230 // images). So append the dyld module back to the list if it is
231 /// unique!
232 if (m_process->GetTarget().GetImages().AppendInNeeded (dyld_module_sp))
233 UpdateImageLoadAddress(dyld_module_sp.get(), m_dyld);
234
235 return true;
236 }
237 }
238 return false;
239}
240
241bool
242DynamicLoaderMacOSXDYLD::NeedToLocateDYLD () const
243{
244 return m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS;
245}
246
247bool
248DynamicLoaderMacOSXDYLD::UpdateCommPageLoadAddress(Module *module)
249{
250 bool changed = false;
251 if (module)
252 {
253 ObjectFile *image_object_file = module->GetObjectFile();
254 if (image_object_file)
255 {
256 SectionList *section_list = image_object_file->GetSectionList ();
257 if (section_list)
258 {
259 uint32_t num_sections = section_list->GetSize();
260 for (uint32_t i=0; i<num_sections; ++i)
261 {
262 Section* section = section_list->GetSectionAtIndex (i).get();
263 if (section)
264 {
265 const addr_t new_section_load_addr = section->GetFileAddress ();
266 const addr_t old_section_load_addr = m_process->GetSectionLoadAddress (section);
267 if (old_section_load_addr == LLDB_INVALID_ADDRESS ||
268 old_section_load_addr != new_section_load_addr)
269 {
270 if (m_process->SectionLoaded (section, section->GetFileAddress ()))
271 changed = true;
272 }
273 }
274 }
275 }
276 }
277 }
278 return changed;
279}
280
281//----------------------------------------------------------------------
282// Update the load addresses for all segments in MODULE using the
283// updated INFO that is passed in.
284//----------------------------------------------------------------------
285bool
286DynamicLoaderMacOSXDYLD::UpdateImageLoadAddress (Module *module, struct DYLDImageInfo& info)
287{
288 bool changed = false;
289 if (module)
290 {
291 ObjectFile *image_object_file = module->GetObjectFile();
292 if (image_object_file)
293 {
294 SectionList *section_list = image_object_file->GetSectionList ();
295 if (section_list)
296 {
297 // All sections listed in the dyld image info structure will all
298 // either be fixed up already, or they will all be off by a single
299 // slide amount that is determined by finding the first segment
300 // that is at file offset zero which also has bytes (a file size
301 // that is greater than zero) in the object file.
302
303 // Determine the slide amount (if any)
304 info.slide = 0;
305 const size_t num_sections = section_list->GetSize();
306 size_t sect_idx = 0;
307 for (sect_idx = 0; sect_idx < num_sections; ++sect_idx)
308 {
309 // Iterate through the object file sections to find the
310 // first section that starts of file offset zero and that
311 // has bytes in the file...
312 Section *section = section_list->GetSectionAtIndex (sect_idx).get();
313 if (section)
314 {
315 // Find the first section that begins at file offset zero
316 // a file size (skip page zero).
317 if (section->GetFileOffset() == 0 && section->GetFileSize() > 0)
318 {
319 // We have now found the section, lets match it up
320 // with the section in the dyld image info structure.
321 const Segment *dyld_segment = info.FindSegment (section->GetName());
322 if (dyld_segment)
323 info.slide = info.address - dyld_segment->addr;
324 // We have found the slide amount, so we can exit
325 // this for loop.
326 break;
327 }
328 }
329 }
330
331 // We now know the slide amount, so go through all sections
332 // and update the load addresses with the correct values.
333 uint32_t num_segments = info.segments.size();
334 for (uint32_t i=0; i<num_segments; ++i)
335 {
336 SectionSP section_sp(section_list->FindSectionByName(info.segments[i].name));
337 assert (section_sp.get() != NULL);
338 const addr_t new_section_load_addr = info.segments[i].addr + info.slide;
339 const addr_t old_section_load_addr = m_process->GetSectionLoadAddress (section_sp.get());
340 if (old_section_load_addr == LLDB_INVALID_ADDRESS ||
341 old_section_load_addr != new_section_load_addr)
342 {
343 if (m_process->SectionLoaded (section_sp.get(), new_section_load_addr))
344 changed = true;
345 }
346 }
347 }
348 }
349 }
350 return changed;
351}
352
353//----------------------------------------------------------------------
354// Update the load addresses for all segments in MODULE using the
355// updated INFO that is passed in.
356//----------------------------------------------------------------------
357bool
358DynamicLoaderMacOSXDYLD::UnloadImageLoadAddress (Module *module, struct DYLDImageInfo& info)
359{
360 bool changed = false;
361 if (module)
362 {
363 ObjectFile *image_object_file = module->GetObjectFile();
364 if (image_object_file)
365 {
366 SectionList *section_list = image_object_file->GetSectionList ();
367 if (section_list)
368 {
369 uint32_t num_segments = info.segments.size();
370 for (uint32_t i=0; i<num_segments; ++i)
371 {
372 SectionSP section_sp(section_list->FindSectionByName(info.segments[i].name));
373 assert (section_sp.get() != NULL);
374 const addr_t old_section_load_addr = info.segments[i].addr + info.slide;
375 if (m_process->SectionUnloaded (section_sp.get(), old_section_load_addr))
376 changed = true;
377 }
378 }
379 }
380 }
381 return changed;
382}
383
384
385//----------------------------------------------------------------------
386// Static callback function that gets called when our DYLD notification
387// breakpoint gets hit. We update all of our image infos and then
388// let our super class DynamicLoader class decide if we should stop
389// or not (based on global preference).
390//----------------------------------------------------------------------
391bool
392DynamicLoaderMacOSXDYLD::NotifyBreakpointHit (void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, lldb::user_id_t break_loc_id)
393{
394 // Let the event know that the images have changed
395 DynamicLoaderMacOSXDYLD* dyld_instance = (DynamicLoaderMacOSXDYLD*) baton;
396 dyld_instance->UpdateAllImageInfos();
397 // Return true to stop the target, false to just let the target run
398 return dyld_instance->GetStopWhenImagesChange();
399}
400
401bool
402DynamicLoaderMacOSXDYLD::ReadAllImageInfosStructure ()
403{
404 Mutex::Locker locker(m_mutex);
405 m_dyld_all_image_infos.Clear();
406 if (m_dyld_all_image_infos_addr != LLDB_INVALID_ADDRESS)
407 {
408 const ByteOrder endian = m_process->GetByteOrder();
409 const uint32_t addr_size = m_process->GetAddressByteSize();
410 uint8_t buf[256];
Jason Molenda1f3af542010-06-10 01:21:21 +0000411 const size_t count_v2 = sizeof (uint32_t) + // version
412 sizeof (uint32_t) + // infoArrayCount
413 addr_size + // infoArray
414 addr_size + // notification
415 addr_size + // processDetachedFromSharedRegion + libSystemInitialized + pad
416 addr_size; // dyldImageLoadAddress
417 const size_t count_v11 = count_v2 +
418 addr_size + // jitInfo
419 addr_size + // dyldVersion
420 addr_size + // errorMessage
421 addr_size + // terminationFlags
422 addr_size + // coreSymbolicationShmPage
423 addr_size + // systemOrderFlag
424 addr_size + // uuidArrayCount
425 addr_size + // uuidArray
426 addr_size + // dyldAllImageInfosAddress
427 addr_size + // initialImageCount
428 addr_size + // errorKind
429 addr_size + // errorClientOfDylibPath
430 addr_size + // errorTargetDylibPath
431 addr_size; // errorSymbol
432 assert (sizeof (buf) > count_v11);
433
434 int count;
Chris Lattner24943d22010-06-08 16:52:24 +0000435 Error error;
Jason Molenda1f3af542010-06-10 01:21:21 +0000436 if (m_process->ReadMemory (m_dyld_all_image_infos_addr, buf, 4, error) == 4)
437 {
438 DataExtractor data(buf, 4, endian, addr_size);
439 uint32_t offset = 0;
440 m_dyld_all_image_infos.version = data.GetU32(&offset);
441 }
442 else
443 {
444 return false;
445 }
446
447 if (m_dyld_all_image_infos.version >= 11)
448 count = count_v11;
449 else
450 count = count_v2;
451
Chris Lattner24943d22010-06-08 16:52:24 +0000452 const size_t bytes_read = m_process->ReadMemory (m_dyld_all_image_infos_addr, buf, count, error);
453 if (bytes_read == count)
454 {
455 DataExtractor data(buf, count, endian, addr_size);
456 uint32_t offset = 0;
457 m_dyld_all_image_infos.version = data.GetU32(&offset);
458 m_dyld_all_image_infos.dylib_info_count = data.GetU32(&offset);
459 m_dyld_all_image_infos.dylib_info_addr = data.GetPointer(&offset);
460 m_dyld_all_image_infos.notification = data.GetPointer(&offset);
461 m_dyld_all_image_infos.processDetachedFromSharedRegion = data.GetU8(&offset);
Jason Molenda1f3af542010-06-10 01:21:21 +0000462 m_dyld_all_image_infos.libSystemInitialized = data.GetU8(&offset);
463 // Adjust for padding.
464 offset += addr_size - 2;
465 m_dyld_all_image_infos.dyldImageLoadAddress = data.GetPointer(&offset);
466 if (m_dyld_all_image_infos.version >= 11)
Chris Lattner24943d22010-06-08 16:52:24 +0000467 {
Jason Molenda1f3af542010-06-10 01:21:21 +0000468 offset += addr_size * 8;
469 uint64_t dyld_all_image_infos_addr = data.GetPointer(&offset);
470
471 // When we started, we were given the actual address of the all_image_infos
472 // struct (probably via TASK_DYLD_INFO) in memory - this address is stored in
473 // m_dyld_all_image_infos_addr and is the most accurate address we have.
474
475 // We read the dyld_all_image_infos struct from memory; it contains its own address.
476 // If the address in the struct does not match the actual address,
477 // the dyld we're looking at has been loaded at a different location (slid) from
478 // where it intended to load. The addresses in the dyld_all_image_infos struct
479 // are the original, non-slid addresses, and need to be adjusted. Most importantly
480 // the address of dyld and the notification address need to be adjusted.
481
482 if (dyld_all_image_infos_addr != m_dyld_all_image_infos_addr)
483 {
484 uint64_t image_infos_offset = dyld_all_image_infos_addr - m_dyld_all_image_infos.dyldImageLoadAddress;
485 uint64_t notification_offset = m_dyld_all_image_infos.notification - m_dyld_all_image_infos.dyldImageLoadAddress;
486 m_dyld_all_image_infos.dyldImageLoadAddress = m_dyld_all_image_infos_addr - image_infos_offset;
487 m_dyld_all_image_infos.notification = m_dyld_all_image_infos.dyldImageLoadAddress + notification_offset;
488 }
Chris Lattner24943d22010-06-08 16:52:24 +0000489 }
490 return true;
491 }
492 }
493 return false;
494}
495
496//----------------------------------------------------------------------
497// If we have found where the "_dyld_all_image_infos" lives in memory,
498// read the current info from it, and then update all image load
499// addresses (or lack thereof).
500//----------------------------------------------------------------------
501uint32_t
502DynamicLoaderMacOSXDYLD::UpdateAllImageInfos()
503{
504 if (ReadAllImageInfosStructure ())
505 {
506 Mutex::Locker locker(m_mutex);
507 uint32_t idx;
Chris Lattner24943d22010-06-08 16:52:24 +0000508 uint32_t i = 0;
509 DYLDImageInfo::collection old_dyld_all_image_infos;
510 old_dyld_all_image_infos.swap(m_dyld_image_infos);
511
512 // If we made it here, we are assuming that the all dylib info data should
513 // be valid, lets read the info array.
514 const ByteOrder endian = m_process->GetByteOrder();
515 const uint32_t addr_size = m_process->GetAddressByteSize();
516
517 if (m_dyld_all_image_infos.dylib_info_count > 0)
518 {
519 if (m_dyld_all_image_infos.dylib_info_addr == 0)
520 {
521 // DYLD is updating the images right now...
522 }
523 else
524 {
525 m_dyld_image_infos.resize(m_dyld_all_image_infos.dylib_info_count);
526 const size_t count = m_dyld_image_infos.size() * 3 * addr_size;
527 DataBufferHeap info_data(count, 0);
528 Error error;
529 const size_t bytes_read = m_process->ReadMemory (m_dyld_all_image_infos.dylib_info_addr,
530 info_data.GetBytes(),
531 info_data.GetByteSize(),
532 error);
533 if (bytes_read == count)
534 {
535 uint32_t info_data_offset = 0;
536 DataExtractor info_data_ref(info_data.GetBytes(), info_data.GetByteSize(), endian, addr_size);
537 for (i = 0; info_data_ref.ValidOffset(info_data_offset); i++)
538 {
539 assert (i < m_dyld_image_infos.size());
540 m_dyld_image_infos[i].address = info_data_ref.GetPointer(&info_data_offset);
541 lldb::addr_t path_addr = info_data_ref.GetPointer(&info_data_offset);
542 m_dyld_image_infos[i].mod_date = info_data_ref.GetPointer(&info_data_offset);
543
544 char raw_path[PATH_MAX];
545 m_process->ReadMemory (path_addr, raw_path, sizeof(raw_path), error);
546 m_dyld_image_infos[i].file_spec.SetFile(raw_path);
547 }
548 assert(i == m_dyld_all_image_infos.dylib_info_count);
549
550 UpdateAllImageInfosHeaderAndLoadCommands();
551 }
552 else
553 {
554 DEBUG_PRINTF( "unable to read all data for all_dylib_infos.");
555 m_dyld_image_infos.clear();
556 }
557 }
558 }
559 else
560 {
561 m_dyld_image_infos.clear();
562 }
563
564 // If our new list is smaller than our old list, we have unloaded
565 // some shared libraries
566 if (m_dyld_image_infos.size() < old_dyld_all_image_infos.size())
567 {
568 ModuleList unloaded_module_list;
569 for (idx = m_dyld_image_infos.size(); idx < old_dyld_all_image_infos.size(); ++idx)
570 {
571 ModuleSP unload_image_module_sp(m_process->GetTarget().GetImages().FindFirstModuleForFileSpec (old_dyld_all_image_infos[idx].file_spec));
572 if (unload_image_module_sp.get())
573 {
574 if (UnloadImageLoadAddress (unload_image_module_sp.get(), old_dyld_all_image_infos[idx]))
575 unloaded_module_list.AppendInNeeded (unload_image_module_sp);
576 }
577 }
578 if (unloaded_module_list.GetSize() > 0)
579 m_process->GetTarget().ModulesDidUnload (unloaded_module_list);
580 }
581 }
582 else
583 {
584 m_dyld_image_infos.clear();
585 }
586
587 const uint32_t num_dylibs = m_dyld_image_infos.size();
588 if (num_dylibs > 0)
589 {
590 ModuleList loaded_module_list;
591 for (uint32_t idx = 0; idx<num_dylibs; ++idx)
592 {
Greg Claytoncf015052010-06-11 03:25:34 +0000593 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 +0000594 ModuleSP image_module_sp(m_process->GetTarget().GetImages().FindFirstModuleForFileSpec (m_dyld_image_infos[idx].file_spec));
595 if (image_module_sp.get() == NULL || image_module_sp->GetArchitecture() != arch_spec)
596 {
597 image_module_sp = m_process->GetTarget().GetSharedModule (m_dyld_image_infos[idx].file_spec,
598 arch_spec,
599 &m_dyld_image_infos[idx].uuid);
600 }
601
602 if (image_module_sp)
603 {
604 ObjectFile *objfile = image_module_sp->GetObjectFile ();
605 if (objfile)
606 {
607 SectionList *sections = objfile->GetSectionList();
608 if (sections)
609 {
610 ConstString commpage_dbstr("__commpage");
611 Section *commpage_section = sections->FindSectionByName(commpage_dbstr).get();
612 if (commpage_section)
613 {
614 FileSpec objfile_file_spec(objfile->GetFileSpec());
615 ModuleSP commpage_image_module_sp(m_process->GetTarget().GetImages().FindFirstModuleForFileSpec (objfile_file_spec, &commpage_dbstr));
616 if (commpage_image_module_sp.get() == NULL)
617 {
618 commpage_image_module_sp = m_process->GetTarget().GetSharedModule (m_dyld_image_infos[idx].file_spec,
619 arch_spec,
620 &m_dyld_image_infos[idx].uuid,
621 &commpage_dbstr,
622 objfile->GetOffset() + commpage_section->GetOffset());
623 UpdateCommPageLoadAddress(commpage_image_module_sp.get());
624 }
625 }
626 }
627 }
628
629 // UpdateImageLoadAddress will return true if any segments
630 // change load address. We need to check this so we don't
631 // mention that all loaded shared libraries are newly loaded
632 // each time we hit out dyld breakpoint since dyld will list all
633 // shared libraries each time.
634 if (UpdateImageLoadAddress (image_module_sp.get(), m_dyld_image_infos[idx]))
635 {
636 loaded_module_list.AppendInNeeded (image_module_sp);
637 }
638 }
639 }
640 PutToLog(DynamicLoaderMacOSXDYLDLog::GetLogIfAllCategoriesSet (1));
641 if (loaded_module_list.GetSize() > 0)
642 {
643 // FIXME: This should really be in the Runtime handlers class, which should get
644 // called by the target's ModulesDidLoad, but we're doing it all locally for now
645 // to save time.
646 // Also, I'm assuming there can be only one libobjc dylib loaded...
647
648 if (m_objc_trampoline_handler_ap.get() == NULL)
649 {
650 size_t num_modules = loaded_module_list.GetSize();
651 for (int i = 0; i < num_modules; i++)
652 {
653 if (ObjCTrampolineHandler::ModuleIsObjCLibrary (loaded_module_list.GetModuleAtIndex (i)))
654 {
655 m_objc_trampoline_handler_ap.reset (new ObjCTrampolineHandler(m_process->GetSP(), loaded_module_list.GetModuleAtIndex (i)));
656 break;
657 }
658 }
659 }
660 m_process->GetTarget().ModulesDidLoad (loaded_module_list);
661 }
662 }
663 return m_dyld_image_infos.size();
664}
665
666//----------------------------------------------------------------------
667// Read a mach_header at ADDR into HEADER, and also fill in the load
668// command data into LOAD_COMMAND_DATA if it is non-NULL.
669//
670// Returns true if we succeed, false if we fail for any reason.
671//----------------------------------------------------------------------
672bool
Greg Clayton1674b122010-07-21 22:12:05 +0000673DynamicLoaderMacOSXDYLD::ReadMachHeader (lldb::addr_t addr, mach_header *header, DataExtractor *load_command_data)
Chris Lattner24943d22010-06-08 16:52:24 +0000674{
Greg Clayton1674b122010-07-21 22:12:05 +0000675 DataBufferHeap header_bytes(sizeof(mach_header), 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000676 Error error;
677 size_t bytes_read = m_process->ReadMemory (addr,
678 header_bytes.GetBytes(),
679 header_bytes.GetByteSize(),
680 error);
Greg Clayton1674b122010-07-21 22:12:05 +0000681 if (bytes_read == sizeof(mach_header))
Chris Lattner24943d22010-06-08 16:52:24 +0000682 {
683 uint32_t offset = 0;
684 ::memset (header, 0, sizeof(header));
685
686 // Get the magic byte unswapped so we can figure out what we are dealing with
687 DataExtractor data(header_bytes.GetBytes(), header_bytes.GetByteSize(), eByteOrderHost, 4);
688 header->magic = data.GetU32(&offset);
689 lldb::addr_t load_cmd_addr = addr;
690 data.SetByteOrder(DynamicLoaderMacOSXDYLD::GetByteOrderFromMagic(header->magic));
691 switch (header->magic)
692 {
Greg Clayton1674b122010-07-21 22:12:05 +0000693 case llvm::MachO::HeaderMagic32:
694 case llvm::MachO::HeaderMagic32Swapped:
Chris Lattner24943d22010-06-08 16:52:24 +0000695 data.SetAddressByteSize(4);
Greg Clayton1674b122010-07-21 22:12:05 +0000696 load_cmd_addr += sizeof(mach_header);
Chris Lattner24943d22010-06-08 16:52:24 +0000697 break;
698
Greg Clayton1674b122010-07-21 22:12:05 +0000699 case llvm::MachO::HeaderMagic64:
700 case llvm::MachO::HeaderMagic64Swapped:
Chris Lattner24943d22010-06-08 16:52:24 +0000701 data.SetAddressByteSize(8);
Greg Clayton1674b122010-07-21 22:12:05 +0000702 load_cmd_addr += sizeof(mach_header_64);
Chris Lattner24943d22010-06-08 16:52:24 +0000703 break;
704
705 default:
706 return false;
707 }
708
709 // Read the rest of dyld's mach header
Greg Clayton1674b122010-07-21 22:12:05 +0000710 if (data.GetU32(&offset, &header->cputype, (sizeof(mach_header)/sizeof(uint32_t)) - 1))
Chris Lattner24943d22010-06-08 16:52:24 +0000711 {
712 if (load_command_data == NULL)
713 return true; // We were able to read the mach_header and weren't asked to read the load command bytes
714
715 DataBufferSP load_cmd_data_sp(new DataBufferHeap(header->sizeofcmds, 0));
716
717 size_t load_cmd_bytes_read = m_process->ReadMemory (load_cmd_addr,
718 load_cmd_data_sp->GetBytes(),
719 load_cmd_data_sp->GetByteSize(),
720 error);
721
722 if (load_cmd_bytes_read == header->sizeofcmds)
723 {
724 // Set the load command data and also set the correct endian
725 // swap settings and the correct address size
726 load_command_data->SetData(load_cmd_data_sp, 0, header->sizeofcmds);
727 load_command_data->SetByteOrder(data.GetByteOrder());
728 load_command_data->SetAddressByteSize(data.GetAddressByteSize());
729 return true; // We successfully read the mach_header and the load command data
730 }
731
732 return false; // We weren't able to read the load command data
733 }
734 }
735 return false; // We failed the read the mach_header
736}
737
738
739//----------------------------------------------------------------------
740// Parse the load commands for an image
741//----------------------------------------------------------------------
742uint32_t
743DynamicLoaderMacOSXDYLD::ParseLoadCommands (const DataExtractor& data, struct DYLDImageInfo& dylib_info, FileSpec *lc_id_dylinker)
744{
745 uint32_t offset = 0;
746 uint32_t cmd_idx;
747 Segment segment;
748 dylib_info.Clear (true);
749
750 for (cmd_idx = 0; cmd_idx < dylib_info.header.ncmds; cmd_idx++)
751 {
752 // Clear out any load command specific data from DYLIB_INFO since
753 // we are about to read it.
754
Greg Clayton1674b122010-07-21 22:12:05 +0000755 if (data.ValidOffsetForDataOfSize (offset, sizeof(load_command)))
Chris Lattner24943d22010-06-08 16:52:24 +0000756 {
Greg Clayton1674b122010-07-21 22:12:05 +0000757 load_command load_cmd;
Chris Lattner24943d22010-06-08 16:52:24 +0000758 uint32_t load_cmd_offset = offset;
759 load_cmd.cmd = data.GetU32 (&offset);
760 load_cmd.cmdsize = data.GetU32 (&offset);
761 switch (load_cmd.cmd)
762 {
Greg Clayton1674b122010-07-21 22:12:05 +0000763 case LoadCommandSegment32:
Chris Lattner24943d22010-06-08 16:52:24 +0000764 {
765 segment.name.SetTrimmedCStringWithLength ((const char *)data.GetData(&offset, 16), 16);
766 segment.addr = data.GetU32 (&offset);
767 segment.size = data.GetU32 (&offset);
768 dylib_info.segments.push_back (segment);
769 }
770 break;
771
Greg Clayton1674b122010-07-21 22:12:05 +0000772 case LoadCommandSegment64:
Chris Lattner24943d22010-06-08 16:52:24 +0000773 {
774 segment.name.SetTrimmedCStringWithLength ((const char *)data.GetData(&offset, 16), 16);
775 segment.addr = data.GetU64 (&offset);
776 segment.size = data.GetU64 (&offset);
777 dylib_info.segments.push_back (segment);
778 }
779 break;
780
Greg Clayton1674b122010-07-21 22:12:05 +0000781 case LoadCommandDynamicLinkerIdent:
Chris Lattner24943d22010-06-08 16:52:24 +0000782 if (lc_id_dylinker)
783 {
784 uint32_t name_offset = load_cmd_offset + data.GetU32 (&offset);
785 const char *path = data.PeekCStr (name_offset);
786 lc_id_dylinker->SetFile (path);
787 }
788 break;
789
Greg Clayton1674b122010-07-21 22:12:05 +0000790 case LoadCommandUUID:
Chris Lattner24943d22010-06-08 16:52:24 +0000791 dylib_info.uuid.SetBytes(data.GetData (&offset, 16));
792 break;
793
794 default:
795 break;
796 }
797 // Set offset to be the beginning of the next load command.
798 offset = load_cmd_offset + load_cmd.cmdsize;
799 }
800 }
801 return cmd_idx;
802}
803
804//----------------------------------------------------------------------
805// Read the mach_header and load commands for each image that the
806// _dyld_all_image_infos structure points to and cache the results.
807//----------------------------------------------------------------------
808void
809DynamicLoaderMacOSXDYLD::UpdateAllImageInfosHeaderAndLoadCommands()
810{
811 uint32_t exe_idx = UINT32_MAX;
812 // Read any UUID values that we can get
813 for (uint32_t i = 0; i < m_dyld_all_image_infos.dylib_info_count; i++)
814 {
815 if (!m_dyld_image_infos[i].UUIDValid())
816 {
817 DataExtractor data; // Load command data
818 if (!ReadMachHeader (m_dyld_image_infos[i].address, &m_dyld_image_infos[i].header, &data))
819 continue;
820
821 ParseLoadCommands (data, m_dyld_image_infos[i], NULL);
822
Greg Clayton1674b122010-07-21 22:12:05 +0000823 if (m_dyld_image_infos[i].header.filetype == HeaderFileTypeExecutable)
Chris Lattner24943d22010-06-08 16:52:24 +0000824 exe_idx = i;
825 }
826 }
827
828 if (exe_idx < m_dyld_image_infos.size())
829 {
830 bool set_executable = false;
Greg Claytoncf015052010-06-11 03:25:34 +0000831 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 +0000832 ModuleSP exe_module_sp(m_process->GetTarget().GetExecutableModule());
833 if (exe_module_sp.get())
834 {
835 if (exe_module_sp->GetFileSpec() != m_dyld_image_infos[exe_idx].file_spec ||
836 exe_module_sp->GetArchitecture() != dyld_exe_arch_spec)
837 set_executable = true;
838 }
839 else
840 set_executable = true;
841
842 if (set_executable)
843 {
844 exe_module_sp = m_process->GetTarget().GetSharedModule (m_dyld_image_infos[exe_idx].file_spec,
845 dyld_exe_arch_spec,
846 &m_dyld_image_infos[exe_idx].uuid);
847 if (exe_module_sp.get())
848 {
849 // If we found the file where it purported to be, then it should
850 // be safe to load dependent images.
851 bool get_dependent_images = exe_module_sp->GetFileSpec() == m_dyld_image_infos[exe_idx].file_spec;
852
853 m_process->GetTarget().SetExecutableModule (exe_module_sp, get_dependent_images);
854 }
855 }
856 }
857}
858
859//----------------------------------------------------------------------
860// Dump a Segment to the file handle provided.
861//----------------------------------------------------------------------
862void
863DynamicLoaderMacOSXDYLD::Segment::PutToLog (Log *log, lldb::addr_t slide) const
864{
865 if (log)
866 log->Printf("\t\t%16s [0x%16.16llx - 0x%16.16llx)", name.AsCString(""), addr + slide, addr + slide + size);
867}
868
869const DynamicLoaderMacOSXDYLD::Segment *
870DynamicLoaderMacOSXDYLD::DYLDImageInfo::FindSegment (const ConstString &name) const
871{
872 const size_t num_segments = segments.size();
873 for (size_t i=0; i<num_segments; ++i)
874 {
875 if (segments[i].name == name)
876 return &segments[i];
877 }
878 return NULL;
879}
880
881
882//----------------------------------------------------------------------
883// Dump an image info structure to the file handle provided.
884//----------------------------------------------------------------------
885void
886DynamicLoaderMacOSXDYLD::DYLDImageInfo::PutToLog (Log *log) const
887{
888 if (log == NULL)
889 return;
890 uint8_t *u = (uint8_t *)uuid.GetBytes();
891
892 if (address == LLDB_INVALID_ADDRESS)
893 {
894 if (u)
895 {
896 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)",
897 mod_date,
898 u[ 0], u[ 1], u[ 2], u[ 3],
899 u[ 4], u[ 5], u[ 6], u[ 7],
900 u[ 8], u[ 9], u[10], u[11],
901 u[12], u[13], u[14], u[15],
902 file_spec.GetDirectory().AsCString(),
903 file_spec.GetFilename().AsCString());
904 }
905 else
906 log->Printf("\t modtime=0x%8.8llx path='%s/%s' (UNLOADED)",
907 mod_date,
908 file_spec.GetDirectory().AsCString(),
909 file_spec.GetFilename().AsCString());
910 }
911 else
912 {
913 if (u)
914 {
915 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'",
916 address,
917 mod_date,
918 u[ 0], u[ 1], u[ 2], u[ 3],
919 u[ 4], u[ 5], u[ 6], u[ 7],
920 u[ 8], u[ 9], u[10], u[11],
921 u[12], u[13], u[14], u[15],
922 file_spec.GetDirectory().AsCString(),
923 file_spec.GetFilename().AsCString());
924 }
925 else
926 {
927 log->Printf("\taddress=0x%16.16llx modtime=0x%8.8llx path='%s/%s'",
928 address,
929 mod_date,
930 file_spec.GetDirectory().AsCString(),
931 file_spec.GetFilename().AsCString());
932
933 }
934 for (uint32_t i=0; i<segments.size(); ++i)
935 segments[i].PutToLog(log, slide);
936 }
937}
938
939//----------------------------------------------------------------------
940// Dump the _dyld_all_image_infos members and all current image infos
941// that we have parsed to the file handle provided.
942//----------------------------------------------------------------------
943void
944DynamicLoaderMacOSXDYLD::PutToLog(Log *log) const
945{
946 if (log == NULL)
947 return;
948
949 Mutex::Locker locker(m_mutex);
950 log->Printf("dyld_all_image_infos = { version=%d, count=%d, addr=0x%8.8llx, notify=0x%8.8llx }",
951 m_dyld_all_image_infos.version,
952 m_dyld_all_image_infos.dylib_info_count,
953 (uint64_t)m_dyld_all_image_infos.dylib_info_addr,
954 (uint64_t)m_dyld_all_image_infos.notification);
955 size_t i;
956 const size_t count = m_dyld_image_infos.size();
957 if (count > 0)
958 {
959 log->Printf("\tdyld_image_infos");
960 for (i = 0; i<count; i++)
961 m_dyld_image_infos[i].PutToLog(log);
962 }
963}
964
965//----------------------------------------------------------------------
966// Static callback function that gets called when the process state
967// changes.
968//----------------------------------------------------------------------
969void
970DynamicLoaderMacOSXDYLD::Initialize(void *baton, Process *process)
971{
972 ((DynamicLoaderMacOSXDYLD*)baton)->PrivateInitialize(process);
973}
974
975void
976DynamicLoaderMacOSXDYLD::PrivateInitialize(Process *process)
977{
978 DEBUG_PRINTF("DynamicLoaderMacOSXDYLD::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState()));
979 Clear(true);
980 m_process = process;
981}
982
983
984//----------------------------------------------------------------------
985// Static callback function that gets called when the process state
986// changes.
987//----------------------------------------------------------------------
988void
989DynamicLoaderMacOSXDYLD::ProcessStateChanged(void *baton, Process *process, StateType state)
990{
991 ((DynamicLoaderMacOSXDYLD*)baton)->PrivateProcessStateChanged(process, state);
992}
993
994bool
995DynamicLoaderMacOSXDYLD::SetNotificationBreakpoint ()
996{
997 DEBUG_PRINTF("DynamicLoaderMacOSXDYLD::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState()));
998 if (m_break_id == LLDB_INVALID_BREAK_ID)
999 {
1000 if (m_dyld_all_image_infos.notification != LLDB_INVALID_ADDRESS)
1001 {
1002 Address so_addr;
1003 // Set the notification breakpoint and install a breakpoint
1004 // callback function that will get called each time the
1005 // breakpoint gets hit. We will use this to track when shared
1006 // libraries get loaded/unloaded.
1007
1008 if (m_process->ResolveLoadAddress(m_dyld_all_image_infos.notification, so_addr))
1009 {
1010 Breakpoint *dyld_break = m_process->GetTarget().CreateBreakpoint (so_addr, true).get();
1011 dyld_break->SetCallback (DynamicLoaderMacOSXDYLD::NotifyBreakpointHit, this, true);
1012 m_break_id = dyld_break->GetID();
1013 }
1014 }
1015 }
1016 return m_break_id != LLDB_INVALID_BREAK_ID;
1017}
1018
1019//----------------------------------------------------------------------Target.h
1020
1021// Member function that gets called when the process state changes.
1022//----------------------------------------------------------------------
1023void
1024DynamicLoaderMacOSXDYLD::PrivateProcessStateChanged (Process *process, StateType state)
1025{
1026 DEBUG_PRINTF("DynamicLoaderMacOSXDYLD::%s(%s)\n", __FUNCTION__, StateAsCString(state));
1027 switch (state)
1028 {
1029 case eStateAttaching:
1030 case eStateLaunching:
1031 case eStateInvalid:
1032 case eStateUnloaded:
1033 case eStateExited:
1034 case eStateDetached:
1035 Clear(false);
1036 break;
1037
1038 case eStateStopped:
1039 // Keep trying find dyld and set our notification breakpoint each time
1040 // we stop until we succeed
1041 if (!DidSetNotificationBreakpoint () && m_process->IsAlive())
1042 {
1043 if (NeedToLocateDYLD ())
1044 LocateDYLD ();
1045
1046 SetNotificationBreakpoint ();
1047 }
1048 break;
1049
1050 case eStateRunning:
1051 case eStateStepping:
1052 case eStateCrashed:
1053 case eStateSuspended:
1054 break;
1055
1056 default:
1057 break;
1058 }
1059}
1060
1061ThreadPlanSP
1062DynamicLoaderMacOSXDYLD::GetStepThroughTrampolinePlan (Thread &thread, bool stop_others)
1063{
1064 ThreadPlanSP thread_plan_sp;
1065 StackFrame *current_frame = thread.GetStackFrameAtIndex(0).get();
1066 const SymbolContext &current_context = current_frame->GetSymbolContext(eSymbolContextSymbol);
1067 Symbol *current_symbol = current_context.symbol;
1068
1069 if (current_symbol != NULL)
1070 {
1071 if (current_symbol->IsTrampoline())
1072 {
1073 const ConstString &trampoline_name = current_symbol->GetMangled().GetName();
1074 if (trampoline_name)
1075 {
1076 SymbolContextList target_symbols;
1077 ModuleList &images = thread.GetProcess().GetTarget().GetImages();
1078 images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeCode, target_symbols);
1079 // FIXME - Make the Run to Address take multiple addresses, and
1080 // run to any of them.
1081 if (target_symbols.GetSize() == 1)
1082 {
1083 SymbolContext context;
1084 AddressRange addr_range;
1085 if (target_symbols.GetContextAtIndex(0, context))
1086 {
1087 context.GetAddressRange (eSymbolContextEverything, addr_range);
1088 thread_plan_sp.reset (new ThreadPlanRunToAddress (thread, addr_range.GetBaseAddress(), stop_others));
1089 }
1090 }
1091 else if (target_symbols.GetSize() > 1)
1092 {
1093 Log *log = DynamicLoaderMacOSXDYLDLog::GetLogIfAllCategoriesSet (1);
1094 if (log)
1095 {
1096 log->Printf ("Found more than one symbol for trampoline target: \"%s\"", trampoline_name.AsCString());
1097 }
1098 }
1099 else
1100 {
1101 Log *log = DynamicLoaderMacOSXDYLDLog::GetLogIfAllCategoriesSet (1);
1102 if (log)
1103 {
1104 log->Printf ("Could not find symbol for trampoline target: \"%s\"", trampoline_name.AsCString());
1105 }
1106 }
1107 }
1108 }
1109 }
1110
1111 if (thread_plan_sp == NULL && m_objc_trampoline_handler_ap.get())
1112 thread_plan_sp = m_objc_trampoline_handler_ap->GetStepThroughDispatchPlan (thread, stop_others);
1113
1114 return thread_plan_sp;
1115}
1116
1117void
1118DynamicLoaderMacOSXDYLD::Initialize()
1119{
1120 PluginManager::RegisterPlugin (GetPluginNameStatic(),
1121 GetPluginDescriptionStatic(),
1122 CreateInstance);
1123}
1124
1125void
1126DynamicLoaderMacOSXDYLD::Terminate()
1127{
1128 PluginManager::UnregisterPlugin (CreateInstance);
1129}
1130
1131
1132const char *
1133DynamicLoaderMacOSXDYLD::GetPluginNameStatic()
1134{
1135 return "dynamic-loader.macosx-dyld";
1136}
1137
1138const char *
1139DynamicLoaderMacOSXDYLD::GetPluginDescriptionStatic()
1140{
1141 return "Dynamic loader plug-in that watches for shared library loads/unloads in MacOSX user processes.";
1142}
1143
1144
1145//------------------------------------------------------------------
1146// PluginInterface protocol
1147//------------------------------------------------------------------
1148const char *
1149DynamicLoaderMacOSXDYLD::GetPluginName()
1150{
1151 return "DynamicLoaderMacOSXDYLD";
1152}
1153
1154const char *
1155DynamicLoaderMacOSXDYLD::GetShortPluginName()
1156{
1157 return GetPluginNameStatic();
1158}
1159
1160uint32_t
1161DynamicLoaderMacOSXDYLD::GetPluginVersion()
1162{
1163 return 1;
1164}
1165
1166void
1167DynamicLoaderMacOSXDYLD::GetPluginCommandHelp (const char *command, Stream *strm)
1168{
1169}
1170
1171Error
1172DynamicLoaderMacOSXDYLD::ExecutePluginCommand (Args &command, Stream *strm)
1173{
1174 Error error;
1175 error.SetErrorString("No plug-in command are currently supported.");
1176 return error;
1177}
1178
1179Log *
1180DynamicLoaderMacOSXDYLD::EnablePluginLogging (Stream *strm, Args &command)
1181{
1182 return NULL;
1183}
1184
1185