1 //===-- DynamicLoaderDarwin.cpp -----------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Breakpoint/StoppointCallbackContext.h"
11 #include "lldb/Core/DataBuffer.h"
12 #include "lldb/Core/DataBufferHeap.h"
13 #include "lldb/Core/Debugger.h"
14 #include "lldb/Core/Log.h"
15 #include "lldb/Core/Module.h"
16 #include "lldb/Core/ModuleSpec.h"
17 #include "lldb/Core/PluginManager.h"
18 #include "lldb/Core/Section.h"
19 #include "lldb/Core/State.h"
20 #include "lldb/Expression/DiagnosticManager.h"
21 #include "lldb/Symbol/ClangASTContext.h"
22 #include "lldb/Symbol/Function.h"
23 #include "lldb/Symbol/ObjectFile.h"
24 #include "lldb/Target/ABI.h"
25 #include "lldb/Target/ObjCLanguageRuntime.h"
26 #include "lldb/Target/RegisterContext.h"
27 #include "lldb/Target/StackFrame.h"
28 #include "lldb/Target/Target.h"
29 #include "lldb/Target/Thread.h"
30 #include "lldb/Target/ThreadPlanCallFunction.h"
31 #include "lldb/Target/ThreadPlanRunToAddress.h"
33 #include "DynamicLoaderDarwin.h"
35 //#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN
36 #ifdef ENABLE_DEBUG_PRINTF
38 #define DEBUG_PRINTF(fmt, ...) printf(fmt, ## __VA_ARGS__)
40 #define DEBUG_PRINTF(fmt, ...)
44 #include "Utility/UuidCompatibility.h"
46 #include <uuid/uuid.h>
50 using namespace lldb_private;
53 //----------------------------------------------------------------------
55 //----------------------------------------------------------------------
56 DynamicLoaderDarwin::DynamicLoaderDarwin (Process* process)
57 : DynamicLoader(process),
59 m_libpthread_module_wp(),
60 m_pthread_getspecific_addr(),
63 m_dyld_image_infos_stop_id(UINT32_MAX),
69 //----------------------------------------------------------------------
71 //----------------------------------------------------------------------
72 DynamicLoaderDarwin::~DynamicLoaderDarwin()
76 //------------------------------------------------------------------
77 /// Called after attaching a process.
79 /// Allow DynamicLoader plug-ins to execute some code after
80 /// attaching to a process.
81 //------------------------------------------------------------------
83 DynamicLoaderDarwin::DidAttach ()
85 PrivateInitialize(m_process);
86 DoInitialImageFetch ();
87 SetNotificationBreakpoint ();
90 //------------------------------------------------------------------
91 /// Called after attaching a process.
93 /// Allow DynamicLoader plug-ins to execute some code after
94 /// attaching to a process.
95 //------------------------------------------------------------------
97 DynamicLoaderDarwin::DidLaunch ()
99 PrivateInitialize(m_process);
100 DoInitialImageFetch ();
101 SetNotificationBreakpoint ();
105 //----------------------------------------------------------------------
106 // Clear out the state of this class.
107 //----------------------------------------------------------------------
109 DynamicLoaderDarwin::Clear (bool clear_process)
111 std::lock_guard<std::recursive_mutex> guard(m_mutex);
114 m_dyld_image_infos.clear();
115 m_dyld_image_infos_stop_id = UINT32_MAX;
120 DynamicLoaderDarwin::FindTargetModuleForImageInfo (ImageInfo &image_info, bool can_create, bool *did_create_ptr)
123 *did_create_ptr = false;
125 Target &target = m_process->GetTarget();
126 const ModuleList &target_images = target.GetImages();
127 ModuleSpec module_spec (image_info.file_spec);
128 module_spec.GetUUID() = image_info.uuid;
129 ModuleSP module_sp (target_images.FindFirstModule (module_spec));
131 if (module_sp && !module_spec.GetUUID().IsValid() && !module_sp->GetUUID().IsValid())
133 // No UUID, we must rely upon the cached module modification
134 // time and the modification time of the file on disk
135 if (module_sp->GetModificationTime() != module_sp->GetFileSpec().GetModificationTime())
143 module_sp = target.GetSharedModule (module_spec);
144 if (!module_sp || module_sp->GetObjectFile() == NULL)
145 module_sp = m_process->ReadModuleFromMemory (image_info.file_spec, image_info.address);
148 *did_create_ptr = (bool) module_sp;
154 DynamicLoaderDarwin::ImageInfo *
155 DynamicLoaderDarwin::FindImageInfoForAddress (addr_t load_address)
157 std::lock_guard<std::recursive_mutex> guard(m_mutex);
158 const size_t image_count = m_dyld_image_infos.size();
159 for (size_t i = 0; i < image_count; i++)
161 if (load_address == m_dyld_image_infos[i].address)
163 return &m_dyld_image_infos[i];
170 DynamicLoaderDarwin::UnloadImages (const std::vector<lldb::addr_t> &solib_addresses)
172 std::lock_guard<std::recursive_mutex> guard(m_mutex);
173 if (m_process->GetStopID() == m_dyld_image_infos_stop_id)
176 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
177 Target &target = m_process->GetTarget();
179 log->Printf ("Removing %" PRId64 " modules.", (uint64_t) solib_addresses.size());
181 ModuleList unloaded_module_list;
183 for (addr_t solib_addr : solib_addresses)
186 if (header.SetLoadAddress (solib_addr, &target))
188 if (header.GetOffset() == 0)
190 ModuleSP module_to_remove (header.GetModule());
191 if (module_to_remove.get())
194 log->Printf ("Removing module at address 0x%" PRIx64, solib_addr);
195 // remove the sections from the Target
196 UnloadSections (module_to_remove);
197 // add this to the list of modules to remove
198 unloaded_module_list.AppendIfNeeded (module_to_remove);
199 // remove the entry from the m_dyld_image_infos
200 ImageInfo::collection::iterator pos, end = m_dyld_image_infos.end();
201 for (pos = m_dyld_image_infos.begin(); pos != end; pos++)
203 if (solib_addr == (*pos).address)
205 m_dyld_image_infos.erase(pos);
214 if (unloaded_module_list.GetSize() > 0)
218 log->PutCString("Unloaded:");
219 unloaded_module_list.LogUUIDAndPaths (log, "DynamicLoaderDarwin::UnloadModules");
221 m_process->GetTarget().GetImages().Remove (unloaded_module_list);
222 m_dyld_image_infos_stop_id = m_process->GetStopID();
226 //----------------------------------------------------------------------
227 // Update the load addresses for all segments in MODULE using the
228 // updated INFO that is passed in.
229 //----------------------------------------------------------------------
231 DynamicLoaderDarwin::UpdateImageLoadAddress (Module *module, ImageInfo& info)
233 bool changed = false;
236 ObjectFile *image_object_file = module->GetObjectFile();
237 if (image_object_file)
239 SectionList *section_list = image_object_file->GetSectionList ();
242 std::vector<uint32_t> inaccessible_segment_indexes;
243 // We now know the slide amount, so go through all sections
244 // and update the load addresses with the correct values.
245 const size_t num_segments = info.segments.size();
246 for (size_t i=0; i<num_segments; ++i)
248 // Only load a segment if it has protections. Things like
249 // __PAGEZERO don't have any protections, and they shouldn't
251 SectionSP section_sp(section_list->FindSectionByName(info.segments[i].name));
253 if (info.segments[i].maxprot == 0)
255 inaccessible_segment_indexes.push_back(i);
259 const addr_t new_section_load_addr = info.segments[i].vmaddr + info.slide;
260 static ConstString g_section_name_LINKEDIT ("__LINKEDIT");
264 // __LINKEDIT sections from files in the shared cache
265 // can overlap so check to see what the segment name is
266 // and pass "false" so we don't warn of overlapping
267 // "Section" objects, and "true" for all other sections.
268 const bool warn_multiple = section_sp->GetName() != g_section_name_LINKEDIT;
270 changed = m_process->GetTarget().SetSectionLoadAddress (section_sp, new_section_load_addr, warn_multiple);
274 Host::SystemLog (Host::eSystemLogWarning,
275 "warning: unable to find and load segment named '%s' at 0x%" PRIx64 " in '%s' in macosx dynamic loader plug-in.\n",
276 info.segments[i].name.AsCString("<invalid>"),
277 (uint64_t)new_section_load_addr,
278 image_object_file->GetFileSpec().GetPath().c_str());
283 // If the loaded the file (it changed) and we have segments that
284 // are not readable or writeable, add them to the invalid memory
285 // region cache for the process. This will typically only be
286 // the __PAGEZERO segment in the main executable. We might be able
287 // to apply this more generally to more sections that have no
288 // protections in the future, but for now we are going to just
290 if (changed && !inaccessible_segment_indexes.empty())
292 for (uint32_t i=0; i<inaccessible_segment_indexes.size(); ++i)
294 const uint32_t seg_idx = inaccessible_segment_indexes[i];
295 SectionSP section_sp(section_list->FindSectionByName(info.segments[seg_idx].name));
299 static ConstString g_pagezero_section_name("__PAGEZERO");
300 if (g_pagezero_section_name == section_sp->GetName())
302 // __PAGEZERO never slides...
303 const lldb::addr_t vmaddr = info.segments[seg_idx].vmaddr;
304 const lldb::addr_t vmsize = info.segments[seg_idx].vmsize;
305 Process::LoadRange pagezero_range (vmaddr, vmsize);
306 m_process->AddInvalidMemoryRegion(pagezero_range);
314 // We might have an in memory image that was loaded as soon as it was created
315 if (info.load_stop_id == m_process->GetStopID())
319 // Update the stop ID when this library was updated
320 info.load_stop_id = m_process->GetStopID();
325 //----------------------------------------------------------------------
326 // Unload the segments in MODULE using the INFO that is passed in.
327 //----------------------------------------------------------------------
329 DynamicLoaderDarwin::UnloadModuleSections (Module *module, ImageInfo& info)
331 bool changed = false;
334 ObjectFile *image_object_file = module->GetObjectFile();
335 if (image_object_file)
337 SectionList *section_list = image_object_file->GetSectionList ();
340 const size_t num_segments = info.segments.size();
341 for (size_t i=0; i<num_segments; ++i)
343 SectionSP section_sp(section_list->FindSectionByName(info.segments[i].name));
346 const addr_t old_section_load_addr = info.segments[i].vmaddr + info.slide;
347 if (m_process->GetTarget().SetSectionUnloaded (section_sp, old_section_load_addr))
352 Host::SystemLog (Host::eSystemLogWarning,
353 "warning: unable to find and unload segment named '%s' in '%s' in macosx dynamic loader plug-in.\n",
354 info.segments[i].name.AsCString("<invalid>"),
355 image_object_file->GetFileSpec().GetPath().c_str());
365 // Given a JSON dictionary (from debugserver, most likely) of binary images loaded in the inferior
366 // process, add the images to the ImageInfo collection.
369 DynamicLoaderDarwin::JSONImageInformationIntoImageInfo (StructuredData::ObjectSP image_details, ImageInfo::collection &image_infos)
371 StructuredData::ObjectSP images_sp = image_details->GetAsDictionary()->GetValueForKey("images");
372 if (images_sp.get() == nullptr)
375 image_infos.resize (images_sp->GetAsArray()->GetSize());
377 for (size_t i = 0; i < image_infos.size(); i++)
379 StructuredData::ObjectSP image_sp = images_sp->GetAsArray()->GetItemAtIndex(i);
380 if (image_sp.get() == nullptr || image_sp->GetAsDictionary() == nullptr)
382 StructuredData::Dictionary *image = image_sp->GetAsDictionary();
383 if (image->HasKey("load_address") == false
384 || image->HasKey("pathname") == false
385 || image->HasKey("mod_date") == false
386 || image->HasKey("mach_header") == false
387 || image->GetValueForKey("mach_header")->GetAsDictionary() == nullptr
388 || image->HasKey("segments") == false
389 || image->GetValueForKey("segments")->GetAsArray() == nullptr
390 || image->HasKey("uuid") == false )
394 image_infos[i].address = image->GetValueForKey("load_address")->GetAsInteger()->GetValue();
395 image_infos[i].mod_date = image->GetValueForKey("mod_date")->GetAsInteger()->GetValue();
396 image_infos[i].file_spec.SetFile(image->GetValueForKey("pathname")->GetAsString()->GetValue().c_str(), false);
398 StructuredData::Dictionary *mh = image->GetValueForKey("mach_header")->GetAsDictionary();
399 image_infos[i].header.magic = mh->GetValueForKey("magic")->GetAsInteger()->GetValue();
400 image_infos[i].header.cputype = mh->GetValueForKey("cputype")->GetAsInteger()->GetValue();
401 image_infos[i].header.cpusubtype = mh->GetValueForKey("cpusubtype")->GetAsInteger()->GetValue();
402 image_infos[i].header.filetype = mh->GetValueForKey("filetype")->GetAsInteger()->GetValue();
404 // Fields that aren't used by DynamicLoaderDarwin so debugserver doesn't currently send them
407 if (mh->HasKey("flags"))
408 image_infos[i].header.flags = mh->GetValueForKey("flags")->GetAsInteger()->GetValue();
410 image_infos[i].header.flags = 0;
412 if (mh->HasKey("ncmds"))
413 image_infos[i].header.ncmds = mh->GetValueForKey("ncmds")->GetAsInteger()->GetValue();
415 image_infos[i].header.ncmds = 0;
417 if (mh->HasKey("sizeofcmds"))
418 image_infos[i].header.sizeofcmds = mh->GetValueForKey("sizeofcmds")->GetAsInteger()->GetValue();
420 image_infos[i].header.sizeofcmds = 0;
422 StructuredData::Array *segments = image->GetValueForKey("segments")->GetAsArray();
423 uint32_t segcount = segments->GetSize();
424 for (size_t j = 0; j < segcount; j++)
427 StructuredData::Dictionary *seg = segments->GetItemAtIndex(j)->GetAsDictionary();
428 segment.name = ConstString(seg->GetValueForKey("name")->GetAsString()->GetValue().c_str());
429 segment.vmaddr = seg->GetValueForKey("vmaddr")->GetAsInteger()->GetValue();
430 segment.vmsize = seg->GetValueForKey("vmsize")->GetAsInteger()->GetValue();
431 segment.fileoff = seg->GetValueForKey("fileoff")->GetAsInteger()->GetValue();
432 segment.filesize = seg->GetValueForKey("filesize")->GetAsInteger()->GetValue();
433 segment.maxprot = seg->GetValueForKey("maxprot")->GetAsInteger()->GetValue();
435 // Fields that aren't used by DynamicLoaderDarwin so debugserver doesn't currently send them
438 if (seg->HasKey("initprot"))
439 segment.initprot = seg->GetValueForKey("initprot")->GetAsInteger()->GetValue();
441 segment.initprot = 0;
443 if (seg->HasKey("flags"))
444 segment.flags = seg->GetValueForKey("flags")->GetAsInteger()->GetValue();
448 if (seg->HasKey("nsects"))
449 segment.nsects = seg->GetValueForKey("nsects")->GetAsInteger()->GetValue();
453 image_infos[i].segments.push_back (segment);
456 image_infos[i].uuid.SetFromCString (image->GetValueForKey("uuid")->GetAsString()->GetValue().c_str());
458 // All sections listed in the dyld image info structure will all
459 // either be fixed up already, or they will all be off by a single
460 // slide amount that is determined by finding the first segment
461 // that is at file offset zero which also has bytes (a file size
462 // that is greater than zero) in the object file.
464 // Determine the slide amount (if any)
465 const size_t num_sections = image_infos[i].segments.size();
466 for (size_t k = 0; k < num_sections; ++k)
468 // Iterate through the object file sections to find the
469 // first section that starts of file offset zero and that
470 // has bytes in the file...
471 if ((image_infos[i].segments[k].fileoff == 0 && image_infos[i].segments[k].filesize > 0)
472 || (image_infos[i].segments[k].name == ConstString("__TEXT")))
474 image_infos[i].slide = image_infos[i].address - image_infos[i].segments[k].vmaddr;
475 // We have found the slide amount, so we can exit
486 DynamicLoaderDarwin::UpdateDYLDImageInfoFromNewImageInfos (ImageInfo::collection &image_infos)
488 const size_t image_infos_size = image_infos.size();
489 for (size_t i = 0; i < image_infos_size; i++)
491 if (image_infos[i].header.filetype == llvm::MachO::MH_DYLINKER)
493 UpdateDYLDImageInfoFromNewImageInfo (image_infos[i]);
494 break; // FIXME simulator debugging w/ multiple dylds
500 DynamicLoaderDarwin::UpdateDYLDImageInfoFromNewImageInfo (ImageInfo &image_info)
502 // FIXME simulator debugging w/ multiple dylds
503 if (image_info.header.filetype == llvm::MachO::MH_DYLINKER)
505 const bool can_create = true;
506 ModuleSP dyld_sp = FindTargetModuleForImageInfo (image_info, can_create, NULL);
509 Target &target = m_process->GetTarget();
510 target.GetImages().AppendIfNeeded (dyld_sp);
511 UpdateImageLoadAddress (dyld_sp.get(), image_info);
512 SetDYLDModule (dyld_sp);
518 DynamicLoaderDarwin::AddExecutableModuleIfInImageInfos (ImageInfo::collection &image_infos)
520 const size_t image_infos_size = image_infos.size();
521 for (size_t i = 0; i < image_infos_size; i++)
523 if (image_infos[i].header.filetype == llvm::MachO::MH_EXECUTE)
525 Target &target = m_process->GetTarget();
526 const bool can_create = true;
527 ModuleSP exe_module_sp (FindTargetModuleForImageInfo (image_infos[i], can_create, NULL));
531 UpdateImageLoadAddress (exe_module_sp.get(), image_infos[i]);
533 if (exe_module_sp.get() != target.GetExecutableModulePointer())
535 // Don't load dependent images since we are in dyld where we will know
536 // and find out about all images that are loaded. Also when setting the
537 // executable module, it will clear the targets module list, and if we
538 // have an in memory dyld module, it will get removed from the list
539 // so we will need to add it back after setting the executable module,
540 // so we first try and see if we already have a weak pointer to the
541 // dyld module, make it into a shared pointer, then add the executable,
542 // then re-add it back to make sure it is always in the list.
544 const bool get_dependent_images = false;
545 m_process->GetTarget().SetExecutableModule (exe_module_sp,
546 get_dependent_images);
548 UpdateDYLDImageInfoFromNewImageInfos (image_infos);
556 DynamicLoaderDarwin::SetDYLDModule (lldb::ModuleSP &dyld_module_sp)
558 m_dyld_module_wp = dyld_module_sp;
562 DynamicLoaderDarwin::GetDYLDModule ()
564 ModuleSP dyld_sp (m_dyld_module_wp.lock());
569 DynamicLoaderDarwin::AddModulesUsingImageInfos (ImageInfo::collection &image_infos)
571 std::lock_guard<std::recursive_mutex> guard(m_mutex);
572 // Now add these images to the main list.
573 ModuleList loaded_module_list;
574 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
575 Target &target = m_process->GetTarget();
576 ModuleList& target_images = target.GetImages();
578 for (uint32_t idx = 0; idx < image_infos.size(); ++idx)
582 log->Printf ("Adding new image at address=0x%16.16" PRIx64 ".", image_infos[idx].address);
583 image_infos[idx].PutToLog (log);
586 m_dyld_image_infos.push_back(image_infos[idx]);
588 ModuleSP image_module_sp (FindTargetModuleForImageInfo (image_infos[idx], true, NULL));
592 ObjectFile *objfile = image_module_sp->GetObjectFile ();
595 SectionList *sections = objfile->GetSectionList();
598 ConstString commpage_dbstr("__commpage");
599 Section *commpage_section = sections->FindSectionByName(commpage_dbstr).get();
600 if (commpage_section)
602 ModuleSpec module_spec (objfile->GetFileSpec(), image_infos[idx].GetArchitecture ());
603 module_spec.GetObjectName() = commpage_dbstr;
604 ModuleSP commpage_image_module_sp(target_images.FindFirstModule (module_spec));
605 if (!commpage_image_module_sp)
607 module_spec.SetObjectOffset (objfile->GetFileOffset() + commpage_section->GetFileOffset());
608 module_spec.SetObjectSize (objfile->GetByteSize());
609 commpage_image_module_sp = target.GetSharedModule (module_spec);
610 if (!commpage_image_module_sp || commpage_image_module_sp->GetObjectFile() == NULL)
612 commpage_image_module_sp = m_process->ReadModuleFromMemory (image_infos[idx].file_spec,
613 image_infos[idx].address);
614 // Always load a memory image right away in the target in case
615 // we end up trying to read the symbol table from memory... The
616 // __LINKEDIT will need to be mapped so we can figure out where
617 // the symbol table bits are...
618 bool changed = false;
619 UpdateImageLoadAddress (commpage_image_module_sp.get(), image_infos[idx]);
620 target.GetImages().Append(commpage_image_module_sp);
623 image_infos[idx].load_stop_id = m_process->GetStopID();
624 loaded_module_list.AppendIfNeeded (commpage_image_module_sp);
632 // UpdateImageLoadAddress will return true if any segments
633 // change load address. We need to check this so we don't
634 // mention that all loaded shared libraries are newly loaded
635 // each time we hit out dyld breakpoint since dyld will list all
636 // shared libraries each time.
637 if (UpdateImageLoadAddress (image_module_sp.get(), image_infos[idx]))
639 target_images.AppendIfNeeded(image_module_sp);
640 loaded_module_list.AppendIfNeeded (image_module_sp);
645 if (loaded_module_list.GetSize() > 0)
648 loaded_module_list.LogUUIDAndPaths (log, "DynamicLoaderDarwin::ModulesDidLoad");
649 m_process->GetTarget().ModulesDidLoad (loaded_module_list);
655 //----------------------------------------------------------------------
656 // On Mac OS X libobjc (the Objective-C runtime) has several critical dispatch
657 // functions written in hand-written assembly, and also have hand-written unwind
658 // information in the eh_frame section. Normally we prefer analyzing the
659 // assembly instructions of a currently executing frame to unwind from that frame --
660 // but on hand-written functions this profiling can fail. We should use the
661 // eh_frame instructions for these functions all the time.
663 // As an aside, it would be better if the eh_frame entries had a flag (or were
664 // extensible so they could have an Apple-specific flag) which indicates that
665 // the instructions are asynchronous -- accurate at every instruction, instead
666 // of our normal default assumption that they are not.
667 //----------------------------------------------------------------------
670 DynamicLoaderDarwin::AlwaysRelyOnEHUnwindInfo (SymbolContext &sym_ctx)
675 module_sp = sym_ctx.symbol->GetAddressRef().GetModule();
677 if (module_sp.get() == NULL && sym_ctx.function)
679 module_sp = sym_ctx.function->GetAddressRange().GetBaseAddress().GetModule();
681 if (module_sp.get() == NULL)
684 ObjCLanguageRuntime *objc_runtime = m_process->GetObjCLanguageRuntime();
685 if (objc_runtime != NULL && objc_runtime->IsModuleObjCLibrary (module_sp))
695 //----------------------------------------------------------------------
696 // Dump a Segment to the file handle provided.
697 //----------------------------------------------------------------------
699 DynamicLoaderDarwin::Segment::PutToLog (Log *log, lldb::addr_t slide) const
704 log->Printf ("\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ")",
707 vmaddr + slide + vmsize);
709 log->Printf ("\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ") slide = 0x%" PRIx64,
712 vmaddr + slide + vmsize,
717 const DynamicLoaderDarwin::Segment *
718 DynamicLoaderDarwin::ImageInfo::FindSegment (const ConstString &name) const
720 const size_t num_segments = segments.size();
721 for (size_t i=0; i<num_segments; ++i)
723 if (segments[i].name == name)
730 //----------------------------------------------------------------------
731 // Dump an image info structure to the file handle provided.
732 //----------------------------------------------------------------------
734 DynamicLoaderDarwin::ImageInfo::PutToLog (Log *log) const
738 const uint8_t *u = (const uint8_t *)uuid.GetBytes();
740 if (address == LLDB_INVALID_ADDRESS)
744 log->Printf("\t modtime=0x%8.8" PRIx64 " uuid=%2.2X%2.2X%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X%2.2X%2.2X%2.2X%2.2X path='%s' (UNLOADED)",
746 u[ 0], u[ 1], u[ 2], u[ 3],
747 u[ 4], u[ 5], u[ 6], u[ 7],
748 u[ 8], u[ 9], u[10], u[11],
749 u[12], u[13], u[14], u[15],
750 file_spec.GetPath().c_str());
753 log->Printf("\t modtime=0x%8.8" PRIx64 " path='%s' (UNLOADED)",
755 file_spec.GetPath().c_str());
761 log->Printf("\taddress=0x%16.16" PRIx64 " modtime=0x%8.8" PRIx64 " uuid=%2.2X%2.2X%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X%2.2X%2.2X%2.2X%2.2X path='%s'",
764 u[ 0], u[ 1], u[ 2], u[ 3],
765 u[ 4], u[ 5], u[ 6], u[ 7],
766 u[ 8], u[ 9], u[10], u[11],
767 u[12], u[13], u[14], u[15],
768 file_spec.GetPath().c_str());
772 log->Printf("\taddress=0x%16.16" PRIx64 " modtime=0x%8.8" PRIx64 " path='%s'",
775 file_spec.GetPath().c_str());
778 for (uint32_t i=0; i<segments.size(); ++i)
779 segments[i].PutToLog(log, slide);
784 DynamicLoaderDarwin::PrivateInitialize(Process *process)
786 DEBUG_PRINTF("DynamicLoaderDarwin::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState()));
789 m_process->GetTarget().ClearAllLoadedSections();
792 //----------------------------------------------------------------------
793 // Member function that gets called when the process state changes.
794 //----------------------------------------------------------------------
796 DynamicLoaderDarwin::PrivateProcessStateChanged (Process *process, StateType state)
798 DEBUG_PRINTF("DynamicLoaderDarwin::%s(%s)\n", __FUNCTION__, StateAsCString(state));
801 case eStateConnected:
802 case eStateAttaching:
803 case eStateLaunching:
812 // Keep trying find dyld and set our notification breakpoint each time
813 // we stop until we succeed
814 if (!DidSetNotificationBreakpoint () && m_process->IsAlive())
816 if (NeedToDoInitialImageFetch ())
817 DoInitialImageFetch ();
819 SetNotificationBreakpoint ();
826 case eStateSuspended:
832 DynamicLoaderDarwin::GetStepThroughTrampolinePlan (Thread &thread, bool stop_others)
834 ThreadPlanSP thread_plan_sp;
835 StackFrame *current_frame = thread.GetStackFrameAtIndex(0).get();
836 const SymbolContext ¤t_context = current_frame->GetSymbolContext(eSymbolContextSymbol);
837 Symbol *current_symbol = current_context.symbol;
838 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
839 TargetSP target_sp (thread.CalculateTarget());
841 if (current_symbol != NULL)
843 std::vector<Address> addresses;
845 if (current_symbol->IsTrampoline())
847 const ConstString &trampoline_name = current_symbol->GetMangled().GetName(current_symbol->GetLanguage(), Mangled::ePreferMangled);
851 const ModuleList &images = target_sp->GetImages();
853 SymbolContextList code_symbols;
854 images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeCode, code_symbols);
855 size_t num_code_symbols = code_symbols.GetSize();
857 if (num_code_symbols > 0)
859 for (uint32_t i = 0; i < num_code_symbols; i++)
861 SymbolContext context;
862 AddressRange addr_range;
863 if (code_symbols.GetContextAtIndex(i, context))
865 context.GetAddressRange (eSymbolContextEverything, 0, false, addr_range);
866 addresses.push_back(addr_range.GetBaseAddress());
869 addr_t load_addr = addr_range.GetBaseAddress().GetLoadAddress(target_sp.get());
871 log->Printf ("Found a trampoline target symbol at 0x%" PRIx64 ".", load_addr);
877 SymbolContextList reexported_symbols;
878 images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeReExported, reexported_symbols);
879 size_t num_reexported_symbols = reexported_symbols.GetSize();
880 if (num_reexported_symbols > 0)
882 for (uint32_t i = 0; i < num_reexported_symbols; i++)
884 SymbolContext context;
885 if (reexported_symbols.GetContextAtIndex(i, context))
889 Symbol *actual_symbol = context.symbol->ResolveReExportedSymbol(*target_sp.get());
892 const Address actual_symbol_addr = actual_symbol->GetAddress();
893 if (actual_symbol_addr.IsValid())
895 addresses.push_back(actual_symbol_addr);
898 lldb::addr_t load_addr = actual_symbol_addr.GetLoadAddress(target_sp.get());
899 log->Printf ("Found a re-exported symbol: %s at 0x%" PRIx64 ".",
900 actual_symbol->GetName().GetCString(), load_addr);
909 SymbolContextList indirect_symbols;
910 images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeResolver, indirect_symbols);
911 size_t num_indirect_symbols = indirect_symbols.GetSize();
912 if (num_indirect_symbols > 0)
914 for (uint32_t i = 0; i < num_indirect_symbols; i++)
916 SymbolContext context;
917 AddressRange addr_range;
918 if (indirect_symbols.GetContextAtIndex(i, context))
920 context.GetAddressRange (eSymbolContextEverything, 0, false, addr_range);
921 addresses.push_back(addr_range.GetBaseAddress());
924 addr_t load_addr = addr_range.GetBaseAddress().GetLoadAddress(target_sp.get());
926 log->Printf ("Found an indirect target symbol at 0x%" PRIx64 ".", load_addr);
933 else if (current_symbol->GetType() == eSymbolTypeReExported)
935 // I am not sure we could ever end up stopped AT a re-exported symbol. But just in case:
937 const Symbol *actual_symbol = current_symbol->ResolveReExportedSymbol(*(target_sp.get()));
940 Address target_addr(actual_symbol->GetAddress());
941 if (target_addr.IsValid())
944 log->Printf ("Found a re-exported symbol: %s pointing to: %s at 0x%" PRIx64 ".",
945 current_symbol->GetName().GetCString(),
946 actual_symbol->GetName().GetCString(),
947 target_addr.GetLoadAddress(target_sp.get()));
948 addresses.push_back (target_addr.GetLoadAddress(target_sp.get()));
954 if (addresses.size() > 0)
956 // First check whether any of the addresses point to Indirect symbols, and if they do, resolve them:
957 std::vector<lldb::addr_t> load_addrs;
958 for (Address address : addresses)
960 Symbol *symbol = address.CalculateSymbolContextSymbol();
961 if (symbol && symbol->IsIndirect())
964 Address symbol_address = symbol->GetAddress();
965 addr_t resolved_addr = thread.GetProcess()->ResolveIndirectFunction(&symbol_address, error);
968 load_addrs.push_back(resolved_addr);
970 log->Printf("ResolveIndirectFunction found resolved target for %s at 0x%" PRIx64 ".",
971 symbol->GetName().GetCString(), resolved_addr);
976 load_addrs.push_back(address.GetLoadAddress(target_sp.get()));
980 thread_plan_sp.reset (new ThreadPlanRunToAddress (thread, load_addrs, stop_others));
986 log->Printf ("Could not find symbol for step through.");
989 return thread_plan_sp;
993 DynamicLoaderDarwin::FindEquivalentSymbols (lldb_private::Symbol *original_symbol,
994 lldb_private::ModuleList &images,
995 lldb_private::SymbolContextList &equivalent_symbols)
997 const ConstString &trampoline_name = original_symbol->GetMangled().GetName(original_symbol->GetLanguage(), Mangled::ePreferMangled);
998 if (!trampoline_name)
1001 size_t initial_size = equivalent_symbols.GetSize();
1003 static const char *resolver_name_regex = "(_gc|_non_gc|\\$[A-Za-z0-9\\$]+)$";
1004 std::string equivalent_regex_buf("^");
1005 equivalent_regex_buf.append (trampoline_name.GetCString());
1006 equivalent_regex_buf.append (resolver_name_regex);
1008 RegularExpression equivalent_name_regex (equivalent_regex_buf.c_str());
1009 const bool append = true;
1010 images.FindSymbolsMatchingRegExAndType (equivalent_name_regex, eSymbolTypeCode, equivalent_symbols, append);
1012 return equivalent_symbols.GetSize() - initial_size;
1016 DynamicLoaderDarwin::GetPThreadLibraryModule()
1018 ModuleSP module_sp = m_libpthread_module_wp.lock();
1021 SymbolContextList sc_list;
1022 ModuleSpec module_spec;
1023 module_spec.GetFileSpec().GetFilename().SetCString("libsystem_pthread.dylib");
1024 ModuleList module_list;
1025 if (m_process->GetTarget().GetImages().FindModules(module_spec, module_list))
1027 if (module_list.GetSize() == 1)
1029 module_sp = module_list.GetModuleAtIndex(0);
1031 m_libpthread_module_wp = module_sp;
1039 DynamicLoaderDarwin::GetPthreadSetSpecificAddress()
1041 if (!m_pthread_getspecific_addr.IsValid())
1043 ModuleSP module_sp = GetPThreadLibraryModule();
1046 lldb_private::SymbolContextList sc_list;
1047 module_sp->FindSymbolsWithNameAndType(ConstString("pthread_getspecific"), eSymbolTypeCode, sc_list);
1049 if (sc_list.GetContextAtIndex(0, sc))
1052 m_pthread_getspecific_addr = sc.symbol->GetAddress();
1056 return m_pthread_getspecific_addr;
1060 DynamicLoaderDarwin::GetThreadLocalData(const lldb::ModuleSP module_sp, const lldb::ThreadSP thread_sp,
1061 lldb::addr_t tls_file_addr)
1063 if (!thread_sp || !module_sp)
1064 return LLDB_INVALID_ADDRESS;
1066 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1068 const uint32_t addr_size = m_process->GetAddressByteSize();
1069 uint8_t buf[sizeof(lldb::addr_t) * 3];
1071 lldb_private::Address tls_addr;
1072 if (module_sp->ResolveFileAddress(tls_file_addr, tls_addr))
1075 const size_t tsl_data_size = addr_size * 3;
1076 Target &target = m_process->GetTarget();
1077 if (target.ReadMemory(tls_addr, false, buf, tsl_data_size, error) == tsl_data_size)
1079 const ByteOrder byte_order = m_process->GetByteOrder();
1080 DataExtractor data(buf, sizeof(buf), byte_order, addr_size);
1081 lldb::offset_t offset = addr_size; // Skip the first pointer
1082 const lldb::addr_t pthread_key = data.GetAddress(&offset);
1083 const lldb::addr_t tls_offset = data.GetAddress(&offset);
1084 if (pthread_key != 0)
1086 // First check to see if we have already figured out the location
1087 // of TLS data for the pthread_key on a specific thread yet. If we
1088 // have we can re-use it since its location will not change unless
1089 // the process execs.
1090 const tid_t tid = thread_sp->GetID();
1091 auto tid_pos = m_tid_to_tls_map.find(tid);
1092 if (tid_pos != m_tid_to_tls_map.end())
1094 auto tls_pos = tid_pos->second.find(pthread_key);
1095 if (tls_pos != tid_pos->second.end())
1097 return tls_pos->second + tls_offset;
1100 StackFrameSP frame_sp = thread_sp->GetStackFrameAtIndex(0);
1103 ClangASTContext *clang_ast_context = target.GetScratchClangASTContext();
1105 if (!clang_ast_context)
1106 return LLDB_INVALID_ADDRESS;
1108 CompilerType clang_void_ptr_type = clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
1109 Address pthread_getspecific_addr = GetPthreadSetSpecificAddress();
1110 if (pthread_getspecific_addr.IsValid())
1112 EvaluateExpressionOptions options;
1114 lldb::ThreadPlanSP thread_plan_sp(
1115 new ThreadPlanCallFunction(*thread_sp, pthread_getspecific_addr, clang_void_ptr_type,
1116 llvm::ArrayRef<lldb::addr_t>(pthread_key), options));
1118 DiagnosticManager execution_errors;
1119 ExecutionContext exe_ctx(thread_sp);
1120 lldb::ExpressionResults results =
1121 m_process->RunThreadPlan(exe_ctx, thread_plan_sp, options, execution_errors);
1123 if (results == lldb::eExpressionCompleted)
1125 lldb::ValueObjectSP result_valobj_sp = thread_plan_sp->GetReturnValueObject();
1126 if (result_valobj_sp)
1128 const lldb::addr_t pthread_key_data = result_valobj_sp->GetValueAsUnsigned(0);
1129 if (pthread_key_data)
1131 m_tid_to_tls_map[tid].insert(std::make_pair(pthread_key, pthread_key_data));
1132 return pthread_key_data + tls_offset;
1141 return LLDB_INVALID_ADDRESS;