]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderDarwin.cpp
Vendor import of lldb release_39 branch r276489:
[FreeBSD/FreeBSD.git] / source / Plugins / DynamicLoader / MacOSX-DYLD / DynamicLoaderDarwin.cpp
1 //===-- DynamicLoaderDarwin.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/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"
32
33 #include "DynamicLoaderDarwin.h"
34
35 //#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN
36 #ifdef ENABLE_DEBUG_PRINTF
37 #include <stdio.h>
38 #define DEBUG_PRINTF(fmt, ...) printf(fmt, ## __VA_ARGS__)
39 #else
40 #define DEBUG_PRINTF(fmt, ...)
41 #endif
42
43 #ifndef __APPLE__
44 #include "Utility/UuidCompatibility.h"
45 #else
46 #include <uuid/uuid.h>
47 #endif
48
49 using namespace lldb;
50 using namespace lldb_private;
51
52
53 //----------------------------------------------------------------------
54 // Constructor
55 //----------------------------------------------------------------------
56 DynamicLoaderDarwin::DynamicLoaderDarwin (Process* process) 
57     : DynamicLoader(process),
58       m_dyld_module_wp(),
59       m_libpthread_module_wp(),
60       m_pthread_getspecific_addr(),
61       m_tid_to_tls_map(),
62       m_dyld_image_infos(),
63       m_dyld_image_infos_stop_id(UINT32_MAX),
64       m_dyld(),
65       m_mutex()
66 {
67 }
68
69 //----------------------------------------------------------------------
70 // Destructor
71 //----------------------------------------------------------------------
72 DynamicLoaderDarwin::~DynamicLoaderDarwin()
73 {
74 }
75
76 //------------------------------------------------------------------
77 /// Called after attaching a process.
78 ///
79 /// Allow DynamicLoader plug-ins to execute some code after
80 /// attaching to a process.
81 //------------------------------------------------------------------
82 void
83 DynamicLoaderDarwin::DidAttach ()
84 {
85     PrivateInitialize(m_process);
86     DoInitialImageFetch ();
87     SetNotificationBreakpoint ();
88 }
89
90 //------------------------------------------------------------------
91 /// Called after attaching a process.
92 ///
93 /// Allow DynamicLoader plug-ins to execute some code after
94 /// attaching to a process.
95 //------------------------------------------------------------------
96 void
97 DynamicLoaderDarwin::DidLaunch ()
98 {
99     PrivateInitialize(m_process);
100     DoInitialImageFetch ();
101     SetNotificationBreakpoint ();
102 }
103
104
105 //----------------------------------------------------------------------
106 // Clear out the state of this class.
107 //----------------------------------------------------------------------
108 void
109 DynamicLoaderDarwin::Clear (bool clear_process)
110 {
111     std::lock_guard<std::recursive_mutex> guard(m_mutex);
112     if (clear_process)
113         m_process = NULL;
114     m_dyld_image_infos.clear();
115     m_dyld_image_infos_stop_id = UINT32_MAX;
116     m_dyld.Clear(false);
117 }
118
119 ModuleSP
120 DynamicLoaderDarwin::FindTargetModuleForImageInfo (ImageInfo &image_info, bool can_create, bool *did_create_ptr)
121 {
122     if (did_create_ptr)
123         *did_create_ptr = false;
124     
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));
130     
131     if (module_sp && !module_spec.GetUUID().IsValid() && !module_sp->GetUUID().IsValid())
132     {
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())
136             module_sp.reset();
137     }
138
139     if (!module_sp)
140     {
141         if (can_create)
142         {
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);
146
147             if (did_create_ptr)
148                 *did_create_ptr = (bool) module_sp;
149         }
150     }
151     return module_sp;
152 }
153
154 DynamicLoaderDarwin::ImageInfo *
155 DynamicLoaderDarwin::FindImageInfoForAddress (addr_t load_address)
156 {
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++)
160     {
161         if (load_address == m_dyld_image_infos[i].address)
162         {
163             return &m_dyld_image_infos[i];
164         }
165     }
166     return NULL;
167 }
168
169 void
170 DynamicLoaderDarwin::UnloadImages (const std::vector<lldb::addr_t> &solib_addresses)
171 {
172     std::lock_guard<std::recursive_mutex> guard(m_mutex);
173     if (m_process->GetStopID() == m_dyld_image_infos_stop_id)
174         return;
175
176     Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
177     Target &target = m_process->GetTarget();
178     if (log)
179         log->Printf ("Removing %" PRId64 " modules.", (uint64_t) solib_addresses.size());
180
181     ModuleList unloaded_module_list;
182
183     for (addr_t solib_addr : solib_addresses)
184     {
185         Address header;
186         if (header.SetLoadAddress (solib_addr, &target))
187         {
188             if (header.GetOffset() == 0)
189             {
190                 ModuleSP module_to_remove (header.GetModule());
191                 if (module_to_remove.get())
192                 {
193                     if (log)
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++)
202                     {
203                         if (solib_addr == (*pos).address)
204                         {
205                             m_dyld_image_infos.erase(pos);
206                             break;
207                         }
208                     }
209                 }
210             }
211         }
212     }
213
214     if (unloaded_module_list.GetSize() > 0)
215     {
216         if (log)
217         {
218             log->PutCString("Unloaded:");
219             unloaded_module_list.LogUUIDAndPaths (log, "DynamicLoaderDarwin::UnloadModules");
220         }
221         m_process->GetTarget().GetImages().Remove (unloaded_module_list);
222         m_dyld_image_infos_stop_id = m_process->GetStopID();
223     }
224 }
225
226 //----------------------------------------------------------------------
227 // Update the load addresses for all segments in MODULE using the
228 // updated INFO that is passed in.
229 //----------------------------------------------------------------------
230 bool
231 DynamicLoaderDarwin::UpdateImageLoadAddress (Module *module, ImageInfo& info)
232 {
233     bool changed = false;
234     if (module)
235     {
236         ObjectFile *image_object_file = module->GetObjectFile();
237         if (image_object_file)
238         {
239             SectionList *section_list = image_object_file->GetSectionList ();
240             if (section_list)
241             {
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)
247                 {
248                     // Only load a segment if it has protections. Things like
249                     // __PAGEZERO don't have any protections, and they shouldn't
250                     // be slid
251                     SectionSP section_sp(section_list->FindSectionByName(info.segments[i].name));
252
253                     if (info.segments[i].maxprot == 0)
254                     {
255                         inaccessible_segment_indexes.push_back(i);
256                     }
257                     else
258                     {
259                         const addr_t new_section_load_addr = info.segments[i].vmaddr + info.slide;
260                         static ConstString g_section_name_LINKEDIT ("__LINKEDIT");
261
262                         if (section_sp)
263                         {
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;
269
270                             changed = m_process->GetTarget().SetSectionLoadAddress (section_sp, new_section_load_addr, warn_multiple);
271                         }
272                         else
273                         {
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());
279                         }
280                     }
281                 }
282                 
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
289                 // do __PAGEZERO.
290                 if (changed && !inaccessible_segment_indexes.empty())
291                 {
292                     for (uint32_t i=0; i<inaccessible_segment_indexes.size(); ++i)
293                     {
294                         const uint32_t seg_idx = inaccessible_segment_indexes[i];
295                         SectionSP section_sp(section_list->FindSectionByName(info.segments[seg_idx].name));
296
297                         if (section_sp)
298                         {
299                             static ConstString g_pagezero_section_name("__PAGEZERO");
300                             if (g_pagezero_section_name == section_sp->GetName())
301                             {
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);
307                             }
308                         }
309                     }
310                 }
311             }
312         }
313     }
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())
316         changed = true;
317     else if (changed)
318     {
319         // Update the stop ID when this library was updated
320         info.load_stop_id = m_process->GetStopID();
321     }
322     return changed;
323 }
324
325 //----------------------------------------------------------------------
326 // Unload the segments in MODULE using the INFO that is passed in.
327 //----------------------------------------------------------------------
328 bool
329 DynamicLoaderDarwin::UnloadModuleSections (Module *module, ImageInfo& info)
330 {
331     bool changed = false;
332     if (module)
333     {
334         ObjectFile *image_object_file = module->GetObjectFile();
335         if (image_object_file)
336         {
337             SectionList *section_list = image_object_file->GetSectionList ();
338             if (section_list)
339             {
340                 const size_t num_segments = info.segments.size();
341                 for (size_t i=0; i<num_segments; ++i)
342                 {
343                     SectionSP section_sp(section_list->FindSectionByName(info.segments[i].name));
344                     if (section_sp)
345                     {
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))
348                             changed = true;
349                     }
350                     else
351                     {
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());
356                     }
357                 }
358             }
359         }
360     }
361     return changed;
362 }
363
364
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.
367
368 bool
369 DynamicLoaderDarwin::JSONImageInformationIntoImageInfo (StructuredData::ObjectSP image_details, ImageInfo::collection &image_infos)
370 {
371     StructuredData::ObjectSP images_sp = image_details->GetAsDictionary()->GetValueForKey("images");
372     if (images_sp.get() == nullptr)
373         return false;
374
375     image_infos.resize (images_sp->GetAsArray()->GetSize());
376
377     for (size_t i = 0; i < image_infos.size(); i++)
378     {
379         StructuredData::ObjectSP image_sp = images_sp->GetAsArray()->GetItemAtIndex(i);
380         if (image_sp.get() == nullptr || image_sp->GetAsDictionary() == nullptr)
381             return false;
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 )
391         {
392             return false;
393         }
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);
397
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();
403
404         // Fields that aren't used by DynamicLoaderDarwin so debugserver doesn't currently send them
405         // in the reply.
406
407         if (mh->HasKey("flags"))
408             image_infos[i].header.flags = mh->GetValueForKey("flags")->GetAsInteger()->GetValue();
409         else
410             image_infos[i].header.flags = 0;
411
412         if (mh->HasKey("ncmds"))
413             image_infos[i].header.ncmds = mh->GetValueForKey("ncmds")->GetAsInteger()->GetValue();
414         else
415             image_infos[i].header.ncmds = 0;
416
417         if (mh->HasKey("sizeofcmds"))
418             image_infos[i].header.sizeofcmds = mh->GetValueForKey("sizeofcmds")->GetAsInteger()->GetValue();
419         else
420             image_infos[i].header.sizeofcmds = 0;
421
422         StructuredData::Array *segments = image->GetValueForKey("segments")->GetAsArray();
423         uint32_t segcount = segments->GetSize();
424         for (size_t j = 0; j < segcount; j++)
425         {
426             Segment segment;
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();
434
435             // Fields that aren't used by DynamicLoaderDarwin so debugserver doesn't currently send them
436             // in the reply.
437
438             if (seg->HasKey("initprot"))
439                 segment.initprot = seg->GetValueForKey("initprot")->GetAsInteger()->GetValue();
440             else
441                 segment.initprot = 0;
442
443             if (seg->HasKey("flags"))
444                 segment.flags = seg->GetValueForKey("flags")->GetAsInteger()->GetValue();
445             else
446                 segment.flags = 0;
447
448             if (seg->HasKey("nsects"))
449                 segment.nsects = seg->GetValueForKey("nsects")->GetAsInteger()->GetValue();
450             else
451                 segment.nsects = 0;
452
453             image_infos[i].segments.push_back (segment);
454         }
455
456         image_infos[i].uuid.SetFromCString (image->GetValueForKey("uuid")->GetAsString()->GetValue().c_str());
457
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.
463     
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)
467         {
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")))
473             {
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
476                 // this for loop.
477                 break;
478             }
479         }
480     }
481
482  return true;
483 }
484
485 void
486 DynamicLoaderDarwin::UpdateDYLDImageInfoFromNewImageInfos (ImageInfo::collection &image_infos)
487 {
488     const size_t image_infos_size = image_infos.size();
489     for (size_t i = 0; i < image_infos_size; i++)
490     {
491         if (image_infos[i].header.filetype == llvm::MachO::MH_DYLINKER)
492         {
493             UpdateDYLDImageInfoFromNewImageInfo (image_infos[i]);
494             break; // FIXME simulator debugging w/ multiple dylds
495         }
496     }
497 }
498
499 void
500 DynamicLoaderDarwin::UpdateDYLDImageInfoFromNewImageInfo (ImageInfo &image_info)
501 {
502     // FIXME simulator debugging w/ multiple dylds
503     if (image_info.header.filetype == llvm::MachO::MH_DYLINKER)
504     {
505         const bool can_create = true;
506         ModuleSP dyld_sp = FindTargetModuleForImageInfo (image_info, can_create, NULL);
507         if (dyld_sp.get())
508         {
509             Target &target = m_process->GetTarget();
510             target.GetImages().AppendIfNeeded (dyld_sp);
511             UpdateImageLoadAddress (dyld_sp.get(), image_info);
512             SetDYLDModule (dyld_sp);
513         }
514     }
515 }
516
517 void
518 DynamicLoaderDarwin::AddExecutableModuleIfInImageInfos (ImageInfo::collection &image_infos)
519 {
520     const size_t image_infos_size = image_infos.size();
521     for (size_t i = 0; i < image_infos_size; i++)
522     {
523         if (image_infos[i].header.filetype == llvm::MachO::MH_EXECUTE)
524         {
525             Target &target = m_process->GetTarget();
526             const bool can_create = true;
527             ModuleSP exe_module_sp (FindTargetModuleForImageInfo (image_infos[i], can_create, NULL));
528     
529             if (exe_module_sp)
530             {
531                 UpdateImageLoadAddress (exe_module_sp.get(), image_infos[i]);
532     
533                 if (exe_module_sp.get() != target.GetExecutableModulePointer())
534                 {
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.
543                     
544                     const bool get_dependent_images = false;
545                     m_process->GetTarget().SetExecutableModule (exe_module_sp, 
546                                                                 get_dependent_images);
547     
548                     UpdateDYLDImageInfoFromNewImageInfos (image_infos);
549                 }
550             }
551         }
552     }
553 }
554
555 void
556 DynamicLoaderDarwin::SetDYLDModule (lldb::ModuleSP &dyld_module_sp)
557 {
558     m_dyld_module_wp = dyld_module_sp;
559 }
560
561 ModuleSP
562 DynamicLoaderDarwin::GetDYLDModule ()
563 {
564     ModuleSP dyld_sp (m_dyld_module_wp.lock());
565     return dyld_sp;
566 }
567
568 bool
569 DynamicLoaderDarwin::AddModulesUsingImageInfos (ImageInfo::collection &image_infos)
570 {
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();
577     
578     for (uint32_t idx = 0; idx < image_infos.size(); ++idx)
579     {
580         if (log)
581         {
582             log->Printf ("Adding new image at address=0x%16.16" PRIx64 ".", image_infos[idx].address);
583             image_infos[idx].PutToLog (log);
584         }
585         
586         m_dyld_image_infos.push_back(image_infos[idx]);
587         
588         ModuleSP image_module_sp (FindTargetModuleForImageInfo (image_infos[idx], true, NULL));
589
590         if (image_module_sp)
591         {
592             ObjectFile *objfile = image_module_sp->GetObjectFile ();
593             if (objfile)
594             {
595                 SectionList *sections = objfile->GetSectionList();
596                 if (sections)
597                 {
598                     ConstString commpage_dbstr("__commpage");
599                     Section *commpage_section = sections->FindSectionByName(commpage_dbstr).get();
600                     if (commpage_section)
601                     {
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)
606                         {
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)
611                             {
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);
621                                 if (changed)
622                                 {
623                                     image_infos[idx].load_stop_id = m_process->GetStopID();
624                                     loaded_module_list.AppendIfNeeded (commpage_image_module_sp);
625                                 }
626                             }
627                         }
628                     }
629                 }
630             }
631
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]))
638             {
639                 target_images.AppendIfNeeded(image_module_sp);
640                 loaded_module_list.AppendIfNeeded (image_module_sp);
641             }
642         }
643     }
644     
645     if (loaded_module_list.GetSize() > 0)
646     {
647         if (log)
648             loaded_module_list.LogUUIDAndPaths (log, "DynamicLoaderDarwin::ModulesDidLoad");
649         m_process->GetTarget().ModulesDidLoad (loaded_module_list);
650     }
651     return true;
652 }
653
654
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.
662 //
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 //----------------------------------------------------------------------
668
669 bool
670 DynamicLoaderDarwin::AlwaysRelyOnEHUnwindInfo (SymbolContext &sym_ctx)
671 {
672     ModuleSP module_sp;
673     if (sym_ctx.symbol)
674     {
675         module_sp = sym_ctx.symbol->GetAddressRef().GetModule();
676     }
677     if (module_sp.get() == NULL && sym_ctx.function)
678     {
679         module_sp = sym_ctx.function->GetAddressRange().GetBaseAddress().GetModule();
680     }
681     if (module_sp.get() == NULL)
682         return false;
683
684     ObjCLanguageRuntime *objc_runtime = m_process->GetObjCLanguageRuntime();
685     if (objc_runtime != NULL && objc_runtime->IsModuleObjCLibrary (module_sp))
686     {
687         return true;
688     }
689
690     return false;
691 }
692
693
694
695 //----------------------------------------------------------------------
696 // Dump a Segment to the file handle provided.
697 //----------------------------------------------------------------------
698 void
699 DynamicLoaderDarwin::Segment::PutToLog (Log *log, lldb::addr_t slide) const
700 {
701     if (log)
702     {
703         if (slide == 0)
704             log->Printf ("\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ")",
705                          name.AsCString(""), 
706                          vmaddr + slide, 
707                          vmaddr + slide + vmsize);
708         else
709             log->Printf ("\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ") slide = 0x%" PRIx64,
710                          name.AsCString(""), 
711                          vmaddr + slide, 
712                          vmaddr + slide + vmsize, 
713                          slide);
714     }
715 }
716
717 const DynamicLoaderDarwin::Segment *
718 DynamicLoaderDarwin::ImageInfo::FindSegment (const ConstString &name) const
719 {
720     const size_t num_segments = segments.size();
721     for (size_t i=0; i<num_segments; ++i)
722     {
723         if (segments[i].name == name)
724             return &segments[i];
725     }
726     return NULL;
727 }
728
729
730 //----------------------------------------------------------------------
731 // Dump an image info structure to the file handle provided.
732 //----------------------------------------------------------------------
733 void
734 DynamicLoaderDarwin::ImageInfo::PutToLog (Log *log) const
735 {
736     if (log == NULL)
737         return;
738     const uint8_t *u = (const uint8_t *)uuid.GetBytes();
739
740     if (address == LLDB_INVALID_ADDRESS)
741     {
742         if (u)
743         {
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)",
745                         mod_date,
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());
751         }
752         else
753             log->Printf("\t                           modtime=0x%8.8" PRIx64 " path='%s' (UNLOADED)",
754                         mod_date,
755                         file_spec.GetPath().c_str());
756     }
757     else
758     {
759         if (u)
760         {
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'",
762                         address,
763                         mod_date,
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());
769         }
770         else
771         {
772             log->Printf("\taddress=0x%16.16" PRIx64 " modtime=0x%8.8" PRIx64 " path='%s'",
773                         address,
774                         mod_date,
775                         file_spec.GetPath().c_str());
776
777         }
778         for (uint32_t i=0; i<segments.size(); ++i)
779             segments[i].PutToLog(log, slide);
780     }
781 }
782
783 void
784 DynamicLoaderDarwin::PrivateInitialize(Process *process)
785 {
786     DEBUG_PRINTF("DynamicLoaderDarwin::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState()));
787     Clear(true);
788     m_process = process;
789     m_process->GetTarget().ClearAllLoadedSections();
790 }
791
792 //----------------------------------------------------------------------
793 // Member function that gets called when the process state changes.
794 //----------------------------------------------------------------------
795 void
796 DynamicLoaderDarwin::PrivateProcessStateChanged (Process *process, StateType state)
797 {
798     DEBUG_PRINTF("DynamicLoaderDarwin::%s(%s)\n", __FUNCTION__, StateAsCString(state));
799     switch (state)
800     {
801     case eStateConnected:
802     case eStateAttaching:
803     case eStateLaunching:
804     case eStateInvalid:
805     case eStateUnloaded:
806     case eStateExited:
807     case eStateDetached:
808         Clear(false);
809         break;
810
811     case eStateStopped:
812         // Keep trying find dyld and set our notification breakpoint each time
813         // we stop until we succeed
814         if (!DidSetNotificationBreakpoint () && m_process->IsAlive())
815         {
816             if (NeedToDoInitialImageFetch ())
817                 DoInitialImageFetch ();
818
819             SetNotificationBreakpoint ();
820         }
821         break;
822
823     case eStateRunning:
824     case eStateStepping:
825     case eStateCrashed:
826     case eStateSuspended:
827         break;
828     }
829 }
830
831 ThreadPlanSP
832 DynamicLoaderDarwin::GetStepThroughTrampolinePlan (Thread &thread, bool stop_others)
833 {
834     ThreadPlanSP thread_plan_sp;
835     StackFrame *current_frame = thread.GetStackFrameAtIndex(0).get();
836     const SymbolContext &current_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());
840
841     if (current_symbol != NULL)
842     {
843         std::vector<Address>  addresses;
844         
845         if (current_symbol->IsTrampoline())
846         {
847             const ConstString &trampoline_name = current_symbol->GetMangled().GetName(current_symbol->GetLanguage(), Mangled::ePreferMangled);
848             
849             if (trampoline_name)
850             {
851                 const ModuleList &images = target_sp->GetImages();
852                 
853                 SymbolContextList code_symbols;
854                 images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeCode, code_symbols);
855                 size_t num_code_symbols = code_symbols.GetSize();
856                 
857                 if (num_code_symbols > 0)
858                 {
859                     for (uint32_t i = 0; i < num_code_symbols; i++)
860                     {
861                         SymbolContext context;
862                         AddressRange addr_range;
863                         if (code_symbols.GetContextAtIndex(i, context))
864                         {
865                             context.GetAddressRange (eSymbolContextEverything, 0, false, addr_range);
866                             addresses.push_back(addr_range.GetBaseAddress());
867                             if (log)
868                             {
869                                 addr_t load_addr = addr_range.GetBaseAddress().GetLoadAddress(target_sp.get());
870
871                                 log->Printf ("Found a trampoline target symbol at 0x%" PRIx64 ".", load_addr);
872                             }
873                         }
874                     }
875                 }
876                 
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)
881                 {
882                     for (uint32_t i = 0; i < num_reexported_symbols; i++)
883                     {
884                         SymbolContext context;
885                         if (reexported_symbols.GetContextAtIndex(i, context))
886                         {
887                             if (context.symbol)
888                             {
889                                 Symbol *actual_symbol = context.symbol->ResolveReExportedSymbol(*target_sp.get());
890                                 if (actual_symbol)
891                                 {
892                                     const Address actual_symbol_addr = actual_symbol->GetAddress();
893                                     if (actual_symbol_addr.IsValid())
894                                     {
895                                         addresses.push_back(actual_symbol_addr);
896                                         if (log)
897                                         {
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);
901                                         }
902                                     }
903                                 }
904                             }
905                         }
906                     }
907                 }
908                 
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)
913                 {
914                     for (uint32_t i = 0; i < num_indirect_symbols; i++)
915                     {
916                         SymbolContext context;
917                         AddressRange addr_range;
918                         if (indirect_symbols.GetContextAtIndex(i, context))
919                         {
920                             context.GetAddressRange (eSymbolContextEverything, 0, false, addr_range);
921                             addresses.push_back(addr_range.GetBaseAddress());
922                             if (log)
923                             {
924                                 addr_t load_addr = addr_range.GetBaseAddress().GetLoadAddress(target_sp.get());
925
926                                 log->Printf ("Found an indirect target symbol at 0x%" PRIx64 ".", load_addr);
927                             }
928                         }
929                     }
930                 }
931             }
932         }
933         else if (current_symbol->GetType() == eSymbolTypeReExported)
934         {
935             // I am not sure we could ever end up stopped AT a re-exported symbol.  But just in case:
936             
937             const Symbol *actual_symbol = current_symbol->ResolveReExportedSymbol(*(target_sp.get()));
938             if (actual_symbol)
939             {
940                 Address target_addr(actual_symbol->GetAddress());
941                 if (target_addr.IsValid())
942                 {
943                     if (log)
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()));
949                 
950                 }
951             }
952         }
953         
954         if (addresses.size() > 0)
955         {
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)
959             {
960                 Symbol *symbol = address.CalculateSymbolContextSymbol();
961                 if (symbol && symbol->IsIndirect())
962                 {
963                     Error error;
964                     Address symbol_address = symbol->GetAddress();
965                     addr_t resolved_addr = thread.GetProcess()->ResolveIndirectFunction(&symbol_address, error);
966                     if (error.Success())
967                     {
968                         load_addrs.push_back(resolved_addr);
969                         if (log)
970                             log->Printf("ResolveIndirectFunction found resolved target for %s at 0x%" PRIx64 ".",
971                                         symbol->GetName().GetCString(), resolved_addr);
972                     }
973                 }
974                 else
975                 {
976                     load_addrs.push_back(address.GetLoadAddress(target_sp.get()));
977                 }
978                 
979             }
980             thread_plan_sp.reset (new ThreadPlanRunToAddress (thread, load_addrs, stop_others));
981         }
982     }
983     else
984     {
985         if (log)
986             log->Printf ("Could not find symbol for step through.");
987     }
988
989     return thread_plan_sp;
990 }
991
992 size_t
993 DynamicLoaderDarwin::FindEquivalentSymbols (lldb_private::Symbol *original_symbol, 
994                                                lldb_private::ModuleList &images, 
995                                                lldb_private::SymbolContextList &equivalent_symbols)
996 {
997     const ConstString &trampoline_name = original_symbol->GetMangled().GetName(original_symbol->GetLanguage(), Mangled::ePreferMangled);
998     if (!trampoline_name)
999         return 0;
1000         
1001     size_t initial_size = equivalent_symbols.GetSize();
1002     
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);
1007
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);
1011     
1012     return equivalent_symbols.GetSize() - initial_size;
1013 }
1014
1015 lldb::ModuleSP
1016 DynamicLoaderDarwin::GetPThreadLibraryModule()
1017 {
1018     ModuleSP module_sp = m_libpthread_module_wp.lock();
1019     if (!module_sp)
1020     {
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))
1026         {
1027             if (module_list.GetSize() == 1)
1028             {
1029                 module_sp = module_list.GetModuleAtIndex(0);
1030                 if (module_sp)
1031                     m_libpthread_module_wp = module_sp;
1032             }
1033         }
1034     }
1035     return module_sp;
1036 }
1037
1038 Address
1039 DynamicLoaderDarwin::GetPthreadSetSpecificAddress()
1040 {
1041     if (!m_pthread_getspecific_addr.IsValid())
1042     {
1043         ModuleSP module_sp = GetPThreadLibraryModule();
1044         if (module_sp)
1045         {
1046             lldb_private::SymbolContextList sc_list;
1047             module_sp->FindSymbolsWithNameAndType(ConstString("pthread_getspecific"), eSymbolTypeCode, sc_list);
1048             SymbolContext sc;
1049             if (sc_list.GetContextAtIndex(0, sc))
1050             {
1051                 if (sc.symbol)
1052                     m_pthread_getspecific_addr = sc.symbol->GetAddress();
1053             }
1054         }
1055     }
1056     return m_pthread_getspecific_addr;
1057 }
1058
1059 lldb::addr_t
1060 DynamicLoaderDarwin::GetThreadLocalData(const lldb::ModuleSP module_sp, const lldb::ThreadSP thread_sp,
1061                                         lldb::addr_t tls_file_addr)
1062 {
1063     if (!thread_sp || !module_sp)
1064         return LLDB_INVALID_ADDRESS;
1065
1066     std::lock_guard<std::recursive_mutex> guard(m_mutex);
1067
1068     const uint32_t addr_size = m_process->GetAddressByteSize();
1069     uint8_t buf[sizeof(lldb::addr_t) * 3];
1070
1071     lldb_private::Address tls_addr;
1072     if (module_sp->ResolveFileAddress(tls_file_addr, tls_addr))
1073     {
1074         Error error;
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)
1078         {
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)
1085             {
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())
1093                 {
1094                     auto tls_pos = tid_pos->second.find(pthread_key);
1095                     if (tls_pos != tid_pos->second.end())
1096                     {
1097                         return tls_pos->second + tls_offset;
1098                     }
1099                 }
1100                 StackFrameSP frame_sp = thread_sp->GetStackFrameAtIndex(0);
1101                 if (frame_sp)
1102                 {
1103                     ClangASTContext *clang_ast_context = target.GetScratchClangASTContext();
1104
1105                     if (!clang_ast_context)
1106                         return LLDB_INVALID_ADDRESS;
1107
1108                     CompilerType clang_void_ptr_type = clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
1109                     Address pthread_getspecific_addr = GetPthreadSetSpecificAddress();
1110                     if (pthread_getspecific_addr.IsValid())
1111                     {
1112                         EvaluateExpressionOptions options;
1113
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));
1117
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);
1122
1123                         if (results == lldb::eExpressionCompleted)
1124                         {
1125                             lldb::ValueObjectSP result_valobj_sp = thread_plan_sp->GetReturnValueObject();
1126                             if (result_valobj_sp)
1127                             {
1128                                 const lldb::addr_t pthread_key_data = result_valobj_sp->GetValueAsUnsigned(0);
1129                                 if (pthread_key_data)
1130                                 {
1131                                     m_tid_to_tls_map[tid].insert(std::make_pair(pthread_key, pthread_key_data));
1132                                     return pthread_key_data + tls_offset;
1133                                 }
1134                             }
1135                         }
1136                     }
1137                 }
1138             }
1139         }
1140     }
1141     return LLDB_INVALID_ADDRESS;
1142 }
1143