DynamicLoaderMacOSXDYLD.cpp revision 6fe03ce1dbc7fff934174ca8add96e6d72f0e126
1//===-- 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/ObjCLanguageRuntime.h"
19#include "lldb/Target/RegisterContext.h"
20#include "lldb/Target/Target.h"
21#include "lldb/Target/Thread.h"
22#include "lldb/Target/ThreadPlanRunToAddress.h"
23#include "lldb/Target/StackFrame.h"
24
25#include "DynamicLoaderMacOSXDYLD.h"
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;
37
38/// FIXME - The ObjC Runtime trampoline handler doesn't really belong here.
39/// I am putting it here so I can invoke it in the Trampoline code here, but
40/// it should be moved to the ObjC Runtime support when it is set up.
41
42
43DynamicLoaderMacOSXDYLD::DYLDImageInfo *
44DynamicLoaderMacOSXDYLD::GetImageInfo (Module *module)
45{
46    const UUID &module_uuid = module->GetUUID();
47    DYLDImageInfo::collection::iterator pos, end = m_dyld_image_infos.end();
48
49    // First try just by UUID as it is the safest.
50    if (module_uuid.IsValid())
51    {
52        for (pos = m_dyld_image_infos.begin(); pos != end; ++pos)
53        {
54            if (pos->uuid == module_uuid)
55                return &(*pos);
56        }
57
58        if (m_dyld.uuid == module_uuid)
59            return &m_dyld;
60    }
61
62    // Next try by platform path only for things that don't have a valid UUID
63    // since if a file has a valid UUID in real life it should also in the
64    // dyld info. This is the next safest because the paths in the dyld info
65    // are platform paths, not local paths. For local debugging platform == local
66    // paths.
67    const FileSpec &platform_file_spec = module->GetPlatformFileSpec();
68    for (pos = m_dyld_image_infos.begin(); pos != end; ++pos)
69    {
70        if (pos->file_spec == platform_file_spec && pos->uuid.IsValid() == false)
71            return &(*pos);
72    }
73
74    if (m_dyld.file_spec == platform_file_spec && m_dyld.uuid.IsValid() == false)
75        return &m_dyld;
76
77    return NULL;
78}
79
80//----------------------------------------------------------------------
81// Create an instance of this class. This function is filled into
82// the plugin info class that gets handed out by the plugin factory and
83// allows the lldb to instantiate an instance of this class.
84//----------------------------------------------------------------------
85DynamicLoader *
86DynamicLoaderMacOSXDYLD::CreateInstance (Process* process, bool force)
87{
88    bool create = force;
89    if (!create)
90    {
91        create = true;
92        Module* exe_module = process->GetTarget().GetExecutableModule().get();
93        if (exe_module)
94        {
95            ObjectFile *object_file = exe_module->GetObjectFile();
96            if (object_file)
97            {
98                SectionList *section_list = object_file->GetSectionList();
99                if (section_list)
100                {
101                    static ConstString g_kld_section_name ("__KLD");
102                    if (section_list->FindSectionByName (g_kld_section_name))
103                    {
104                        create = false;
105                    }
106                }
107            }
108        }
109
110        if (create)
111        {
112            const llvm::Triple &triple_ref = process->GetTarget().GetArchitecture().GetTriple();
113            create = triple_ref.getOS() == llvm::Triple::Darwin && triple_ref.getVendor() == llvm::Triple::Apple;
114        }
115    }
116
117    if (create)
118        return new DynamicLoaderMacOSXDYLD (process);
119    return NULL;
120}
121
122//----------------------------------------------------------------------
123// Constructor
124//----------------------------------------------------------------------
125DynamicLoaderMacOSXDYLD::DynamicLoaderMacOSXDYLD (Process* process) :
126    DynamicLoader(process),
127    m_dyld(),
128    m_dyld_all_image_infos_addr(LLDB_INVALID_ADDRESS),
129    m_dyld_all_image_infos(),
130    m_dyld_all_image_infos_stop_id (UINT32_MAX),
131    m_break_id(LLDB_INVALID_BREAK_ID),
132    m_dyld_image_infos(),
133    m_dyld_image_infos_stop_id (UINT32_MAX),
134    m_mutex(Mutex::eMutexTypeRecursive)
135{
136}
137
138//----------------------------------------------------------------------
139// Destructor
140//----------------------------------------------------------------------
141DynamicLoaderMacOSXDYLD::~DynamicLoaderMacOSXDYLD()
142{
143    Clear(true);
144}
145
146//------------------------------------------------------------------
147/// Called after attaching a process.
148///
149/// Allow DynamicLoader plug-ins to execute some code after
150/// attaching to a process.
151//------------------------------------------------------------------
152void
153DynamicLoaderMacOSXDYLD::DidAttach ()
154{
155    PrivateInitialize(m_process);
156    LocateDYLD ();
157    SetNotificationBreakpoint ();
158}
159
160//------------------------------------------------------------------
161/// Called after attaching a process.
162///
163/// Allow DynamicLoader plug-ins to execute some code after
164/// attaching to a process.
165//------------------------------------------------------------------
166void
167DynamicLoaderMacOSXDYLD::DidLaunch ()
168{
169    PrivateInitialize(m_process);
170    LocateDYLD ();
171    SetNotificationBreakpoint ();
172}
173
174
175//----------------------------------------------------------------------
176// Clear out the state of this class.
177//----------------------------------------------------------------------
178void
179DynamicLoaderMacOSXDYLD::Clear (bool clear_process)
180{
181    Mutex::Locker locker(m_mutex);
182
183    if (m_process->IsAlive() && LLDB_BREAK_ID_IS_VALID(m_break_id))
184        m_process->ClearBreakpointSiteByID(m_break_id);
185
186    if (clear_process)
187        m_process = NULL;
188    m_dyld.Clear(false);
189    m_dyld_all_image_infos_addr = LLDB_INVALID_ADDRESS;
190    m_dyld_all_image_infos.Clear();
191    m_break_id = LLDB_INVALID_BREAK_ID;
192    m_dyld_image_infos.clear();
193}
194
195//----------------------------------------------------------------------
196// Check if we have found DYLD yet
197//----------------------------------------------------------------------
198bool
199DynamicLoaderMacOSXDYLD::DidSetNotificationBreakpoint() const
200{
201    return LLDB_BREAK_ID_IS_VALID (m_break_id);
202}
203
204//----------------------------------------------------------------------
205// Try and figure out where dyld is by first asking the Process
206// if it knows (which currently calls down in the the lldb::Process
207// to get the DYLD info (available on SnowLeopard only). If that fails,
208// then check in the default addresses.
209//----------------------------------------------------------------------
210bool
211DynamicLoaderMacOSXDYLD::LocateDYLD()
212{
213    if (m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS)
214        m_dyld_all_image_infos_addr = m_process->GetImageInfoAddress ();
215
216    if (m_dyld_all_image_infos_addr != LLDB_INVALID_ADDRESS)
217    {
218        if (ReadAllImageInfosStructure ())
219        {
220            if (m_dyld_all_image_infos.dyldImageLoadAddress != LLDB_INVALID_ADDRESS)
221                return ReadDYLDInfoFromMemoryAndSetNotificationCallback (m_dyld_all_image_infos.dyldImageLoadAddress);
222            else
223                return ReadDYLDInfoFromMemoryAndSetNotificationCallback (m_dyld_all_image_infos_addr & 0xfffffffffff00000ull);
224        }
225    }
226
227    // Check some default values
228    Module *executable = m_process->GetTarget().GetExecutableModule().get();
229
230    if (executable)
231    {
232        if (executable->GetArchitecture().GetAddressByteSize() == 8)
233        {
234            return ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x7fff5fc00000ull);
235        }
236#if defined (__arm__)
237        else
238        {
239            ArchSpec arm_arch("arm");
240            if (arm_arch == executable->Arch())
241                return ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x2fe00000);
242        }
243#endif
244        return ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x8fe00000);
245    }
246    return false;
247}
248
249ModuleSP
250DynamicLoaderMacOSXDYLD::FindTargetModuleForDYLDImageInfo (const DYLDImageInfo &image_info, bool can_create, bool *did_create_ptr)
251{
252    if (did_create_ptr)
253        *did_create_ptr = false;
254    ModuleSP module_sp;
255    ModuleList &target_images = m_process->GetTarget().GetImages();
256    const bool image_info_uuid_is_valid = image_info.uuid.IsValid();
257    if (image_info_uuid_is_valid)
258        module_sp = target_images.FindModule(image_info.uuid);
259
260    if (!module_sp)
261    {
262        ArchSpec arch(image_info.GetArchitecture ());
263
264        module_sp = target_images.FindFirstModuleForFileSpec (image_info.file_spec, &arch, NULL);
265
266        if (can_create && !module_sp)
267        {
268            module_sp = m_process->GetTarget().GetSharedModule (image_info.file_spec,
269                                                                arch,
270                                                                image_info_uuid_is_valid ? &image_info.uuid : NULL);
271            if (did_create_ptr)
272                *did_create_ptr = module_sp;
273        }
274    }
275    return module_sp;
276}
277
278//----------------------------------------------------------------------
279// Assume that dyld is in memory at ADDR and try to parse it's load
280// commands
281//----------------------------------------------------------------------
282bool
283DynamicLoaderMacOSXDYLD::ReadDYLDInfoFromMemoryAndSetNotificationCallback(lldb::addr_t addr)
284{
285    DataExtractor data; // Load command data
286    if (ReadMachHeader (addr, &m_dyld.header, &data))
287    {
288        if (m_dyld.header.filetype == llvm::MachO::HeaderFileTypeDynamicLinkEditor)
289        {
290            m_dyld.address = addr;
291            ModuleSP dyld_module_sp;
292            if (ParseLoadCommands (data, m_dyld, &m_dyld.file_spec))
293            {
294                if (m_dyld.file_spec)
295                {
296                    dyld_module_sp = FindTargetModuleForDYLDImageInfo (m_dyld, true, NULL);
297
298                    if (dyld_module_sp)
299                        UpdateImageLoadAddress (dyld_module_sp.get(), m_dyld);
300                }
301            }
302
303            if (m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS && dyld_module_sp.get())
304            {
305                static ConstString g_dyld_all_image_infos ("dyld_all_image_infos");
306                const Symbol *symbol = dyld_module_sp->FindFirstSymbolWithNameAndType (g_dyld_all_image_infos, eSymbolTypeData);
307                if (symbol)
308                    m_dyld_all_image_infos_addr = symbol->GetValue().GetLoadAddress(&m_process->GetTarget());
309            }
310
311            // Update all image infos
312            InitializeFromAllImageInfos ();
313
314            // If we didn't have an executable before, but now we do, then the
315            // dyld module shared pointer might be unique and we may need to add
316            // it again (since Target::SetExecutableModule() will clear the
317            // images). So append the dyld module back to the list if it is
318            /// unique!
319            if (dyld_module_sp && m_process->GetTarget().GetImages().AppendIfNeeded (dyld_module_sp))
320                UpdateImageLoadAddress(dyld_module_sp.get(), m_dyld);
321
322            return true;
323        }
324    }
325    return false;
326}
327
328bool
329DynamicLoaderMacOSXDYLD::NeedToLocateDYLD () const
330{
331    return m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS;
332}
333
334bool
335DynamicLoaderMacOSXDYLD::UpdateCommPageLoadAddress(Module *module)
336{
337    bool changed = false;
338    if (module)
339    {
340        ObjectFile *image_object_file = module->GetObjectFile();
341        if (image_object_file)
342        {
343            SectionList *section_list = image_object_file->GetSectionList ();
344            if (section_list)
345            {
346                uint32_t num_sections = section_list->GetSize();
347                for (uint32_t i=0; i<num_sections; ++i)
348                {
349                    Section* section = section_list->GetSectionAtIndex (i).get();
350                    if (section)
351                    {
352                        const addr_t new_section_load_addr = section->GetFileAddress ();
353                        const addr_t old_section_load_addr = m_process->GetTarget().GetSectionLoadList().GetSectionLoadAddress (section);
354                        if (old_section_load_addr == LLDB_INVALID_ADDRESS ||
355                            old_section_load_addr != new_section_load_addr)
356                        {
357                            if (m_process->GetTarget().GetSectionLoadList().SetSectionLoadAddress (section, section->GetFileAddress ()))
358                                changed = true;
359                        }
360                    }
361                }
362            }
363        }
364    }
365    return changed;
366}
367
368//----------------------------------------------------------------------
369// Update the load addresses for all segments in MODULE using the
370// updated INFO that is passed in.
371//----------------------------------------------------------------------
372bool
373DynamicLoaderMacOSXDYLD::UpdateImageLoadAddress (Module *module, DYLDImageInfo& info)
374{
375    bool changed = false;
376    if (module)
377    {
378        ObjectFile *image_object_file = module->GetObjectFile();
379        if (image_object_file)
380        {
381            SectionList *section_list = image_object_file->GetSectionList ();
382            if (section_list)
383            {
384                // We now know the slide amount, so go through all sections
385                // and update the load addresses with the correct values.
386                uint32_t num_segments = info.segments.size();
387                for (uint32_t i=0; i<num_segments; ++i)
388                {
389                    SectionSP section_sp(section_list->FindSectionByName(info.segments[i].name));
390                    const addr_t new_section_load_addr = info.segments[i].vmaddr + info.slide;
391                    if (section_sp)
392                    {
393                        const addr_t old_section_load_addr = m_process->GetTarget().GetSectionLoadList().GetSectionLoadAddress (section_sp.get());
394                        if (old_section_load_addr == LLDB_INVALID_ADDRESS ||
395                            old_section_load_addr != new_section_load_addr)
396                        {
397                            if (m_process->GetTarget().GetSectionLoadList().SetSectionLoadAddress (section_sp.get(), new_section_load_addr))
398                                changed = true;
399                        }
400                    }
401                    else
402                    {
403                        fprintf (stderr,
404                                 "warning: unable to find and load segment named '%s' at 0x%llx in '%s/%s' in macosx dynamic loader plug-in.\n",
405                                 info.segments[i].name.AsCString("<invalid>"),
406                                 (uint64_t)new_section_load_addr,
407                                 image_object_file->GetFileSpec().GetDirectory().AsCString(),
408                                 image_object_file->GetFileSpec().GetFilename().AsCString());
409                    }
410                }
411            }
412        }
413    }
414    return changed;
415}
416
417//----------------------------------------------------------------------
418// Update the load addresses for all segments in MODULE using the
419// updated INFO that is passed in.
420//----------------------------------------------------------------------
421bool
422DynamicLoaderMacOSXDYLD::UnloadImageLoadAddress (Module *module, DYLDImageInfo& info)
423{
424    bool changed = false;
425    if (module)
426    {
427        ObjectFile *image_object_file = module->GetObjectFile();
428        if (image_object_file)
429        {
430            SectionList *section_list = image_object_file->GetSectionList ();
431            if (section_list)
432            {
433                uint32_t num_segments = info.segments.size();
434                for (uint32_t i=0; i<num_segments; ++i)
435                {
436                    SectionSP section_sp(section_list->FindSectionByName(info.segments[i].name));
437                    if (section_sp)
438                    {
439                        const addr_t old_section_load_addr = info.segments[i].vmaddr + info.slide;
440                        if (m_process->GetTarget().GetSectionLoadList().SetSectionUnloaded (section_sp.get(), old_section_load_addr))
441                            changed = true;
442                    }
443                    else
444                    {
445                        fprintf (stderr,
446                                 "warning: unable to find and unload segment named '%s' in '%s/%s' in macosx dynamic loader plug-in.\n",
447                                 info.segments[i].name.AsCString("<invalid>"),
448                                 image_object_file->GetFileSpec().GetDirectory().AsCString(),
449                                 image_object_file->GetFileSpec().GetFilename().AsCString());
450                    }
451                }
452            }
453        }
454    }
455    return changed;
456}
457
458
459//----------------------------------------------------------------------
460// Static callback function that gets called when our DYLD notification
461// breakpoint gets hit. We update all of our image infos and then
462// let our super class DynamicLoader class decide if we should stop
463// or not (based on global preference).
464//----------------------------------------------------------------------
465bool
466DynamicLoaderMacOSXDYLD::NotifyBreakpointHit (void *baton,
467                                              StoppointCallbackContext *context,
468                                              lldb::user_id_t break_id,
469                                              lldb::user_id_t break_loc_id)
470{
471    // Let the event know that the images have changed
472    // DYLD passes three arguments to the notification breakpoint.
473    // Arg1: enum dyld_image_mode mode - 0 = adding, 1 = removing
474    // Arg2: uint32_t infoCount        - Number of shared libraries added
475    // Arg3: dyld_image_info info[]    - Array of structs of the form:
476    //                                     const struct mach_header *imageLoadAddress
477    //                                     const char               *imageFilePath
478    //                                     uintptr_t                 imageFileModDate (a time_t)
479
480    DynamicLoaderMacOSXDYLD* dyld_instance = (DynamicLoaderMacOSXDYLD*) baton;
481
482    // First step is to see if we've already initialized the all image infos.  If we haven't then this function
483    // will do so and return true.  In the course of initializing the all_image_infos it will read the complete
484    // current state, so we don't need to figure out what has changed from the data passed in to us.
485
486    if (dyld_instance->InitializeFromAllImageInfos())
487        return dyld_instance->GetStopWhenImagesChange();
488
489    Process *process = context->exe_ctx.process;
490    const lldb::ABISP &abi = process->GetABI();
491    if (abi != NULL)
492    {
493        // Build up the value array to store the three arguments given above, then get the values from the ABI:
494
495        ClangASTContext *clang_ast_context = process->GetTarget().GetScratchClangASTContext();
496        ValueList argument_values;
497        Value input_value;
498
499        void *clang_void_ptr_type = clang_ast_context->GetVoidPtrType(false);
500        void *clang_uint32_type   = clang_ast_context->GetBuiltinTypeForEncodingAndBitSize(lldb::eEncodingUint, 32);
501        input_value.SetValueType (Value::eValueTypeScalar);
502        input_value.SetContext (Value::eContextTypeClangType, clang_uint32_type);
503        argument_values.PushValue(input_value);
504        argument_values.PushValue(input_value);
505        input_value.SetContext (Value::eContextTypeClangType, clang_void_ptr_type);
506        argument_values.PushValue (input_value);
507
508        if (abi->GetArgumentValues (*context->exe_ctx.thread, argument_values))
509        {
510            uint32_t dyld_mode = argument_values.GetValueAtIndex(0)->GetScalar().UInt (-1);
511            if (dyld_mode != -1)
512            {
513                // Okay the mode was right, now get the number of elements, and the array of new elements...
514                uint32_t image_infos_count = argument_values.GetValueAtIndex(1)->GetScalar().UInt (-1);
515                if (image_infos_count != -1)
516                {
517                    // Got the number added, now go through the array of added elements, putting out the mach header
518                    // address, and adding the image.
519                    // Note, I'm not putting in logging here, since the AddModules & RemoveModules functions do
520                    // all the logging internally.
521
522                    lldb::addr_t image_infos_addr = argument_values.GetValueAtIndex(2)->GetScalar().ULongLong();
523                    if (dyld_mode == 0)
524                    {
525                        // This is add:
526                        dyld_instance->AddModulesUsingImageInfosAddress (image_infos_addr, image_infos_count);
527                    }
528                    else
529                    {
530                        // This is remove:
531                        dyld_instance->RemoveModulesUsingImageInfosAddress (image_infos_addr, image_infos_count);
532                    }
533
534                }
535            }
536        }
537    }
538
539    // Return true to stop the target, false to just let the target run
540    return dyld_instance->GetStopWhenImagesChange();
541}
542
543bool
544DynamicLoaderMacOSXDYLD::ReadAllImageInfosStructure ()
545{
546    Mutex::Locker locker(m_mutex);
547
548    // the all image infos is already valid for this process stop ID
549    if (m_process->GetStopID() == m_dyld_all_image_infos_stop_id)
550        return true;
551
552    m_dyld_all_image_infos.Clear();
553    if (m_dyld_all_image_infos_addr != LLDB_INVALID_ADDRESS)
554    {
555        ByteOrder byte_order = m_process->GetTarget().GetArchitecture().GetByteOrder();
556        uint32_t addr_size = 4;
557        if (m_dyld_all_image_infos_addr > UINT32_MAX)
558            addr_size = 8;
559
560        uint8_t buf[256];
561        DataExtractor data (buf, sizeof(buf), byte_order, addr_size);
562        uint32_t offset = 0;
563
564        const size_t count_v2 =  sizeof (uint32_t) + // version
565                                 sizeof (uint32_t) + // infoArrayCount
566                                 addr_size +         // infoArray
567                                 addr_size +         // notification
568                                 addr_size +         // processDetachedFromSharedRegion + libSystemInitialized + pad
569                                 addr_size;          // dyldImageLoadAddress
570        const size_t count_v11 = count_v2 +
571                                 addr_size +         // jitInfo
572                                 addr_size +         // dyldVersion
573                                 addr_size +         // errorMessage
574                                 addr_size +         // terminationFlags
575                                 addr_size +         // coreSymbolicationShmPage
576                                 addr_size +         // systemOrderFlag
577                                 addr_size +         // uuidArrayCount
578                                 addr_size +         // uuidArray
579                                 addr_size +         // dyldAllImageInfosAddress
580                                 addr_size +         // initialImageCount
581                                 addr_size +         // errorKind
582                                 addr_size +         // errorClientOfDylibPath
583                                 addr_size +         // errorTargetDylibPath
584                                 addr_size;          // errorSymbol
585        assert (sizeof (buf) >= count_v11);
586
587        int count;
588        Error error;
589        if (m_process->ReadMemory (m_dyld_all_image_infos_addr, buf, 4, error) == 4)
590        {
591            m_dyld_all_image_infos.version = data.GetU32(&offset);
592            // If anything in the high byte is set, we probably got the byte
593            // order incorrect (the process might not have it set correctly
594            // yet due to attaching to a program without a specified file).
595            if (m_dyld_all_image_infos.version & 0xff000000)
596            {
597                // We have guessed the wrong byte order. Swap it and try
598                // reading the version again.
599                if (byte_order == eByteOrderLittle)
600                    byte_order = eByteOrderBig;
601                else
602                    byte_order = eByteOrderLittle;
603
604                data.SetByteOrder (byte_order);
605                offset = 0;
606                m_dyld_all_image_infos.version = data.GetU32(&offset);
607            }
608        }
609        else
610        {
611            return false;
612        }
613
614        if (m_dyld_all_image_infos.version >= 11)
615            count = count_v11;
616        else
617            count = count_v2;
618
619        const size_t bytes_read = m_process->ReadMemory (m_dyld_all_image_infos_addr, buf, count, error);
620        if (bytes_read == count)
621        {
622            offset = 0;
623            m_dyld_all_image_infos.version = data.GetU32(&offset);
624            m_dyld_all_image_infos.dylib_info_count = data.GetU32(&offset);
625            m_dyld_all_image_infos.dylib_info_addr = data.GetPointer(&offset);
626            m_dyld_all_image_infos.notification = data.GetPointer(&offset);
627            m_dyld_all_image_infos.processDetachedFromSharedRegion = data.GetU8(&offset);
628            m_dyld_all_image_infos.libSystemInitialized = data.GetU8(&offset);
629            // Adjust for padding.
630            offset += addr_size - 2;
631            m_dyld_all_image_infos.dyldImageLoadAddress = data.GetPointer(&offset);
632            if (m_dyld_all_image_infos.version >= 11)
633            {
634                offset += addr_size * 8;
635                uint64_t dyld_all_image_infos_addr = data.GetPointer(&offset);
636
637                // When we started, we were given the actual address of the all_image_infos
638                // struct (probably via TASK_DYLD_INFO) in memory - this address is stored in
639                // m_dyld_all_image_infos_addr and is the most accurate address we have.
640
641                // We read the dyld_all_image_infos struct from memory; it contains its own address.
642                // If the address in the struct does not match the actual address,
643                // the dyld we're looking at has been loaded at a different location (slid) from
644                // where it intended to load.  The addresses in the dyld_all_image_infos struct
645                // are the original, non-slid addresses, and need to be adjusted.  Most importantly
646                // the address of dyld and the notification address need to be adjusted.
647
648                if (dyld_all_image_infos_addr != m_dyld_all_image_infos_addr)
649                {
650                    uint64_t image_infos_offset = dyld_all_image_infos_addr - m_dyld_all_image_infos.dyldImageLoadAddress;
651                    uint64_t notification_offset = m_dyld_all_image_infos.notification - m_dyld_all_image_infos.dyldImageLoadAddress;
652                    m_dyld_all_image_infos.dyldImageLoadAddress = m_dyld_all_image_infos_addr - image_infos_offset;
653                    m_dyld_all_image_infos.notification = m_dyld_all_image_infos.dyldImageLoadAddress + notification_offset;
654                }
655            }
656            m_dyld_all_image_infos_stop_id = m_process->GetStopID();
657            return true;
658        }
659    }
660    return false;
661}
662
663
664bool
665DynamicLoaderMacOSXDYLD::AddModulesUsingImageInfosAddress (lldb::addr_t image_infos_addr, uint32_t image_infos_count)
666{
667    DYLDImageInfo::collection image_infos;
668    LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
669    if (log)
670        log->Printf ("Adding %d modules.\n");
671
672    Mutex::Locker locker(m_mutex);
673    if (m_process->GetStopID() == m_dyld_image_infos_stop_id)
674        return true;
675
676    if (!ReadImageInfos (image_infos_addr, image_infos_count, image_infos))
677        return false;
678
679    UpdateImageInfosHeaderAndLoadCommands (image_infos, image_infos_count, false);
680    bool return_value = AddModulesUsingImageInfos (image_infos);
681    m_dyld_image_infos_stop_id = m_process->GetStopID();
682    return return_value;
683}
684
685// Adds the modules in image_infos to m_dyld_image_infos.
686// NB don't call this passing in m_dyld_image_infos.
687
688bool
689DynamicLoaderMacOSXDYLD::AddModulesUsingImageInfos (DYLDImageInfo::collection &image_infos)
690{
691    // Now add these images to the main list.
692    ModuleList loaded_module_list;
693    LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
694
695    for (uint32_t idx = 0; idx < image_infos.size(); ++idx)
696    {
697        if (log)
698        {
699            log->Printf ("Adding new image at address=0x%16.16llx.", image_infos[idx].address);
700            image_infos[idx].PutToLog (log.get());
701        }
702
703        m_dyld_image_infos.push_back(image_infos[idx]);
704
705        ModuleSP image_module_sp (FindTargetModuleForDYLDImageInfo (image_infos[idx], true, NULL));
706
707        if (image_module_sp)
708        {
709            if (image_infos[idx].header.filetype == llvm::MachO::HeaderFileTypeDynamicLinkEditor)
710                image_module_sp->SetIsDynamicLinkEditor (true);
711
712            ObjectFile *objfile = image_module_sp->GetObjectFile ();
713            if (objfile)
714            {
715                SectionList *sections = objfile->GetSectionList();
716                if (sections)
717                {
718                    ConstString commpage_dbstr("__commpage");
719                    Section *commpage_section = sections->FindSectionByName(commpage_dbstr).get();
720                    if (commpage_section)
721                    {
722                        ModuleList& target_images = m_process->GetTarget().GetImages();
723                        const FileSpec objfile_file_spec = objfile->GetFileSpec();
724                        ArchSpec arch (image_infos[idx].GetArchitecture ());
725                        ModuleSP commpage_image_module_sp(target_images.FindFirstModuleForFileSpec (objfile_file_spec,
726                                                                                                    &arch,
727                                                                                                    &commpage_dbstr));
728                        if (!commpage_image_module_sp)
729                        {
730                            commpage_image_module_sp
731                                    = m_process->GetTarget().GetSharedModule (image_infos[idx].file_spec,
732                                                                              arch,
733                                                                              NULL,
734                                                                              &commpage_dbstr,
735                                                                              objfile->GetOffset() + commpage_section->GetFileOffset());
736                        }
737                        if (commpage_image_module_sp)
738                            UpdateCommPageLoadAddress (commpage_image_module_sp.get());
739                    }
740                }
741            }
742
743            // UpdateImageLoadAddress will return true if any segments
744            // change load address. We need to check this so we don't
745            // mention that all loaded shared libraries are newly loaded
746            // each time we hit out dyld breakpoint since dyld will list all
747            // shared libraries each time.
748            if (UpdateImageLoadAddress (image_module_sp.get(), image_infos[idx]))
749            {
750                loaded_module_list.AppendIfNeeded (image_module_sp);
751            }
752        }
753    }
754
755    if (loaded_module_list.GetSize() > 0)
756    {
757        // FIXME: This should really be in the Runtime handlers class, which should get
758        // called by the target's ModulesDidLoad, but we're doing it all locally for now
759        // to save time.
760        // Also, I'm assuming there can be only one libobjc dylib loaded...
761
762        ObjCLanguageRuntime *objc_runtime = m_process->GetObjCLanguageRuntime();
763        if (objc_runtime != NULL && !objc_runtime->HasReadObjCLibrary())
764        {
765            size_t num_modules = loaded_module_list.GetSize();
766            for (int i = 0; i < num_modules; i++)
767            {
768                if (objc_runtime->IsModuleObjCLibrary (loaded_module_list.GetModuleAtIndex (i)))
769                {
770                    objc_runtime->ReadObjCLibrary (loaded_module_list.GetModuleAtIndex (i));
771                    break;
772                }
773            }
774        }
775        if (log)
776            loaded_module_list.LogUUIDAndPaths (log, "DynamicLoaderMacOSXDYLD::ModulesDidLoad");
777        m_process->GetTarget().ModulesDidLoad (loaded_module_list);
778    }
779    return true;
780}
781
782bool
783DynamicLoaderMacOSXDYLD::RemoveModulesUsingImageInfosAddress (lldb::addr_t image_infos_addr, uint32_t image_infos_count)
784{
785    DYLDImageInfo::collection image_infos;
786    LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
787
788    Mutex::Locker locker(m_mutex);
789    if (m_process->GetStopID() == m_dyld_image_infos_stop_id)
790        return true;
791
792    // First read in the image_infos for the removed modules, and their headers & load commands.
793    if (!ReadImageInfos (image_infos_addr, image_infos_count, image_infos))
794    {
795        if (log)
796            log->PutCString ("Failed reading image infos array.");
797        return false;
798    }
799
800    if (log)
801        log->Printf ("Removing %d modules.", image_infos_count);
802
803    ModuleList unloaded_module_list;
804    for (uint32_t idx = 0; idx < image_infos.size(); ++idx)
805    {
806        if (log)
807        {
808            log->Printf ("Removing module at address=0x%16.16llx.", image_infos[idx].address);
809            image_infos[idx].PutToLog (log.get());
810        }
811
812        // Remove this image_infos from the m_all_image_infos.  We do the comparision by address
813        // rather than by file spec because we can have many modules with the same "file spec" in the
814        // case that they are modules loaded from memory.
815        //
816        // Also copy over the uuid from the old entry to the removed entry so we can
817        // use it to lookup the module in the module list.
818
819        DYLDImageInfo::collection::iterator pos, end = m_dyld_image_infos.end();
820        for (pos = m_dyld_image_infos.begin(); pos != end; pos++)
821        {
822            if (image_infos[idx].address == (*pos).address)
823            {
824                image_infos[idx].uuid = (*pos).uuid;
825
826                // Add the module from this image_info to the "unloaded_module_list".  We'll remove them all at
827                // one go later on.
828
829                ModuleSP unload_image_module_sp (FindTargetModuleForDYLDImageInfo (image_infos[idx], false, NULL));
830                if (unload_image_module_sp.get())
831                {
832                    UnloadImageLoadAddress (unload_image_module_sp.get(), image_infos[idx]);
833                    unloaded_module_list.AppendIfNeeded (unload_image_module_sp);
834                }
835                else
836                {
837                    if (log)
838                    {
839                        log->Printf ("Could not find module for unloading info entry:");
840                        image_infos[idx].PutToLog(log.get());
841                    }
842                }
843
844                // Then remove it from the m_dyld_image_infos:
845
846                m_dyld_image_infos.erase(pos);
847                break;
848            }
849        }
850
851        if (pos == end)
852        {
853            if (log)
854            {
855                log->Printf ("Could not find image_info entry for unloading image:");
856                image_infos[idx].PutToLog(log.get());
857            }
858        }
859    }
860    if (unloaded_module_list.GetSize() > 0)
861    {
862        if (log)
863        {
864            log->PutCString("Unloaded:");
865            unloaded_module_list.LogUUIDAndPaths (log, "DynamicLoaderMacOSXDYLD::ModulesDidUnload");
866        }
867        m_process->GetTarget().ModulesDidUnload (unloaded_module_list);
868    }
869    m_dyld_image_infos_stop_id = m_process->GetStopID();
870    return true;
871}
872
873bool
874DynamicLoaderMacOSXDYLD::ReadImageInfos (lldb::addr_t image_infos_addr,
875                                         uint32_t image_infos_count,
876                                         DYLDImageInfo::collection &image_infos)
877{
878    const ByteOrder endian = m_dyld.GetByteOrder();
879    const uint32_t addr_size = m_dyld.GetAddressByteSize();
880
881    image_infos.resize(image_infos_count);
882    const size_t count = image_infos.size() * 3 * addr_size;
883    DataBufferHeap info_data(count, 0);
884    Error error;
885    const size_t bytes_read = m_process->ReadMemory (image_infos_addr,
886                                                     info_data.GetBytes(),
887                                                     info_data.GetByteSize(),
888                                                     error);
889    if (bytes_read == count)
890    {
891        uint32_t info_data_offset = 0;
892        DataExtractor info_data_ref(info_data.GetBytes(), info_data.GetByteSize(), endian, addr_size);
893        for (int i = 0; i < image_infos.size() && info_data_ref.ValidOffset(info_data_offset); i++)
894        {
895            image_infos[i].address = info_data_ref.GetPointer(&info_data_offset);
896            lldb::addr_t path_addr = info_data_ref.GetPointer(&info_data_offset);
897            image_infos[i].mod_date = info_data_ref.GetPointer(&info_data_offset);
898
899            char raw_path[PATH_MAX];
900            m_process->ReadCStringFromMemory (path_addr, raw_path, sizeof(raw_path));
901            // don't resolve the path
902            const bool resolve_path = false;
903            image_infos[i].file_spec.SetFile(raw_path, resolve_path);
904        }
905        return true;
906    }
907    else
908    {
909        return false;
910    }
911}
912
913//----------------------------------------------------------------------
914// If we have found where the "_dyld_all_image_infos" lives in memory,
915// read the current info from it, and then update all image load
916// addresses (or lack thereof).  Only do this if this is the first time
917// we're reading the dyld infos.  Return true if we actually read anything,
918// and false otherwise.
919//----------------------------------------------------------------------
920bool
921DynamicLoaderMacOSXDYLD::InitializeFromAllImageInfos ()
922{
923    LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
924
925    Mutex::Locker locker(m_mutex);
926    if (m_process->GetStopID() == m_dyld_image_infos_stop_id
927          || m_dyld_image_infos.size() != 0)
928        return false;
929
930    if (ReadAllImageInfosStructure ())
931    {
932        if (m_dyld_all_image_infos.dylib_info_count > 0)
933        {
934            if (m_dyld_all_image_infos.dylib_info_addr == 0)
935            {
936                // DYLD is updating the images now.  So we should say we have no images, and then we'll
937                // figure it out when we hit the added breakpoint.
938                return false;
939            }
940            else
941            {
942                if (!AddModulesUsingImageInfosAddress (m_dyld_all_image_infos.dylib_info_addr,
943                                                       m_dyld_all_image_infos.dylib_info_count))
944                {
945                    DEBUG_PRINTF( "unable to read all data for all_dylib_infos.");
946                    m_dyld_image_infos.clear();
947                }
948            }
949        }
950        return true;
951    }
952    else
953        return false;
954}
955
956//----------------------------------------------------------------------
957// Read a mach_header at ADDR into HEADER, and also fill in the load
958// command data into LOAD_COMMAND_DATA if it is non-NULL.
959//
960// Returns true if we succeed, false if we fail for any reason.
961//----------------------------------------------------------------------
962bool
963DynamicLoaderMacOSXDYLD::ReadMachHeader (lldb::addr_t addr, llvm::MachO::mach_header *header, DataExtractor *load_command_data)
964{
965    DataBufferHeap header_bytes(sizeof(llvm::MachO::mach_header), 0);
966    Error error;
967    size_t bytes_read = m_process->ReadMemory (addr,
968                                               header_bytes.GetBytes(),
969                                               header_bytes.GetByteSize(),
970                                               error);
971    if (bytes_read == sizeof(llvm::MachO::mach_header))
972    {
973        uint32_t offset = 0;
974        ::memset (header, 0, sizeof(llvm::MachO::mach_header));
975
976        // Get the magic byte unswapped so we can figure out what we are dealing with
977        DataExtractor data(header_bytes.GetBytes(), header_bytes.GetByteSize(), lldb::endian::InlHostByteOrder(), 4);
978        header->magic = data.GetU32(&offset);
979        lldb::addr_t load_cmd_addr = addr;
980        data.SetByteOrder(DynamicLoaderMacOSXDYLD::GetByteOrderFromMagic(header->magic));
981        switch (header->magic)
982        {
983        case llvm::MachO::HeaderMagic32:
984        case llvm::MachO::HeaderMagic32Swapped:
985            data.SetAddressByteSize(4);
986            load_cmd_addr += sizeof(llvm::MachO::mach_header);
987            break;
988
989        case llvm::MachO::HeaderMagic64:
990        case llvm::MachO::HeaderMagic64Swapped:
991            data.SetAddressByteSize(8);
992            load_cmd_addr += sizeof(llvm::MachO::mach_header_64);
993            break;
994
995        default:
996            return false;
997        }
998
999        // Read the rest of dyld's mach header
1000        if (data.GetU32(&offset, &header->cputype, (sizeof(llvm::MachO::mach_header)/sizeof(uint32_t)) - 1))
1001        {
1002            if (load_command_data == NULL)
1003                return true; // We were able to read the mach_header and weren't asked to read the load command bytes
1004
1005            DataBufferSP load_cmd_data_sp(new DataBufferHeap(header->sizeofcmds, 0));
1006
1007            size_t load_cmd_bytes_read = m_process->ReadMemory (load_cmd_addr,
1008                                                                load_cmd_data_sp->GetBytes(),
1009                                                                load_cmd_data_sp->GetByteSize(),
1010                                                                error);
1011
1012            if (load_cmd_bytes_read == header->sizeofcmds)
1013            {
1014                // Set the load command data and also set the correct endian
1015                // swap settings and the correct address size
1016                load_command_data->SetData(load_cmd_data_sp, 0, header->sizeofcmds);
1017                load_command_data->SetByteOrder(data.GetByteOrder());
1018                load_command_data->SetAddressByteSize(data.GetAddressByteSize());
1019                return true; // We successfully read the mach_header and the load command data
1020            }
1021
1022            return false; // We weren't able to read the load command data
1023        }
1024    }
1025    return false; // We failed the read the mach_header
1026}
1027
1028
1029//----------------------------------------------------------------------
1030// Parse the load commands for an image
1031//----------------------------------------------------------------------
1032uint32_t
1033DynamicLoaderMacOSXDYLD::ParseLoadCommands (const DataExtractor& data, DYLDImageInfo& dylib_info, FileSpec *lc_id_dylinker)
1034{
1035    uint32_t offset = 0;
1036    uint32_t cmd_idx;
1037    Segment segment;
1038    dylib_info.Clear (true);
1039
1040    for (cmd_idx = 0; cmd_idx < dylib_info.header.ncmds; cmd_idx++)
1041    {
1042        // Clear out any load command specific data from DYLIB_INFO since
1043        // we are about to read it.
1044
1045        if (data.ValidOffsetForDataOfSize (offset, sizeof(llvm::MachO::load_command)))
1046        {
1047            llvm::MachO::load_command load_cmd;
1048            uint32_t load_cmd_offset = offset;
1049            load_cmd.cmd = data.GetU32 (&offset);
1050            load_cmd.cmdsize = data.GetU32 (&offset);
1051            switch (load_cmd.cmd)
1052            {
1053            case llvm::MachO::LoadCommandSegment32:
1054                {
1055                    segment.name.SetTrimmedCStringWithLength ((const char *)data.GetData(&offset, 16), 16);
1056                    // We are putting 4 uint32_t values 4 uint64_t values so
1057                    // we have to use multiple 32 bit gets below.
1058                    segment.vmaddr = data.GetU32 (&offset);
1059                    segment.vmsize = data.GetU32 (&offset);
1060                    segment.fileoff = data.GetU32 (&offset);
1061                    segment.filesize = data.GetU32 (&offset);
1062                    // Extract maxprot, initprot, nsects and flags all at once
1063                    data.GetU32(&offset, &segment.maxprot, 4);
1064                    dylib_info.segments.push_back (segment);
1065                }
1066                break;
1067
1068            case llvm::MachO::LoadCommandSegment64:
1069                {
1070                    segment.name.SetTrimmedCStringWithLength ((const char *)data.GetData(&offset, 16), 16);
1071                    // Extract vmaddr, vmsize, fileoff, and filesize all at once
1072                    data.GetU64(&offset, &segment.vmaddr, 4);
1073                    // Extract maxprot, initprot, nsects and flags all at once
1074                    data.GetU32(&offset, &segment.maxprot, 4);
1075                    dylib_info.segments.push_back (segment);
1076                }
1077                break;
1078
1079            case llvm::MachO::LoadCommandDynamicLinkerIdent:
1080                if (lc_id_dylinker)
1081                {
1082                    uint32_t name_offset = load_cmd_offset + data.GetU32 (&offset);
1083                    const char *path = data.PeekCStr (name_offset);
1084                    lc_id_dylinker->SetFile (path, true);
1085                }
1086                break;
1087
1088            case llvm::MachO::LoadCommandUUID:
1089                dylib_info.uuid.SetBytes(data.GetData (&offset, 16));
1090                break;
1091
1092            default:
1093                break;
1094            }
1095            // Set offset to be the beginning of the next load command.
1096            offset = load_cmd_offset + load_cmd.cmdsize;
1097        }
1098    }
1099
1100    // All sections listed in the dyld image info structure will all
1101    // either be fixed up already, or they will all be off by a single
1102    // slide amount that is determined by finding the first segment
1103    // that is at file offset zero which also has bytes (a file size
1104    // that is greater than zero) in the object file.
1105
1106    // Determine the slide amount (if any)
1107    const size_t num_sections = dylib_info.segments.size();
1108    for (size_t i = 0; i < num_sections; ++i)
1109    {
1110        // Iterate through the object file sections to find the
1111        // first section that starts of file offset zero and that
1112        // has bytes in the file...
1113        if (dylib_info.segments[i].fileoff == 0 && dylib_info.segments[i].filesize > 0)
1114        {
1115            dylib_info.slide = dylib_info.address - dylib_info.segments[i].vmaddr;
1116            // We have found the slide amount, so we can exit
1117            // this for loop.
1118            break;
1119        }
1120    }
1121    return cmd_idx;
1122}
1123
1124//----------------------------------------------------------------------
1125// Read the mach_header and load commands for each image that the
1126// _dyld_all_image_infos structure points to and cache the results.
1127//----------------------------------------------------------------------
1128
1129void
1130DynamicLoaderMacOSXDYLD::UpdateImageInfosHeaderAndLoadCommands(DYLDImageInfo::collection &image_infos,
1131                                                               uint32_t infos_count,
1132                                                               bool update_executable)
1133{
1134    uint32_t exe_idx = UINT32_MAX;
1135    LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
1136    // Read any UUID values that we can get
1137    for (uint32_t i = 0; i < infos_count; i++)
1138    {
1139        if (!image_infos[i].UUIDValid())
1140        {
1141            DataExtractor data; // Load command data
1142            if (!ReadMachHeader (image_infos[i].address, &image_infos[i].header, &data))
1143                continue;
1144
1145            ParseLoadCommands (data, image_infos[i], NULL);
1146
1147            if (image_infos[i].header.filetype == llvm::MachO::HeaderFileTypeExecutable)
1148                exe_idx = i;
1149
1150        }
1151    }
1152
1153    if (exe_idx < image_infos.size())
1154    {
1155        ModuleSP exe_module_sp (FindTargetModuleForDYLDImageInfo (image_infos[exe_idx], false, NULL));
1156
1157        if (!exe_module_sp)
1158        {
1159            ArchSpec exe_arch_spec (image_infos[exe_idx].GetArchitecture ());
1160            exe_module_sp = m_process->GetTarget().GetSharedModule (image_infos[exe_idx].file_spec,
1161                                                                    exe_arch_spec,
1162                                                                    &image_infos[exe_idx].uuid);
1163        }
1164
1165        if (exe_module_sp)
1166        {
1167            if (exe_module_sp.get() != m_process->GetTarget().GetExecutableModule().get())
1168            {
1169                // Don't load dependent images since we are in dyld where we will know
1170                // and find out about all images that are loaded
1171                bool get_dependent_images = false;
1172                m_process->GetTarget().SetExecutableModule (exe_module_sp,
1173                                                            get_dependent_images);
1174            }
1175        }
1176    }
1177}
1178
1179//----------------------------------------------------------------------
1180// Dump a Segment to the file handle provided.
1181//----------------------------------------------------------------------
1182void
1183DynamicLoaderMacOSXDYLD::Segment::PutToLog (Log *log, lldb::addr_t slide) const
1184{
1185    if (log)
1186    {
1187        if (slide == 0)
1188            log->Printf ("\t\t%16s [0x%16.16llx - 0x%16.16llx)",
1189                         name.AsCString(""),
1190                         vmaddr + slide,
1191                         vmaddr + slide + vmsize);
1192        else
1193            log->Printf ("\t\t%16s [0x%16.16llx - 0x%16.16llx) slide = 0x%llx",
1194                         name.AsCString(""),
1195                         vmaddr + slide,
1196                         vmaddr + slide + vmsize,
1197                         slide);
1198    }
1199}
1200
1201const DynamicLoaderMacOSXDYLD::Segment *
1202DynamicLoaderMacOSXDYLD::DYLDImageInfo::FindSegment (const ConstString &name) const
1203{
1204    const size_t num_segments = segments.size();
1205    for (size_t i=0; i<num_segments; ++i)
1206    {
1207        if (segments[i].name == name)
1208            return &segments[i];
1209    }
1210    return NULL;
1211}
1212
1213
1214//----------------------------------------------------------------------
1215// Dump an image info structure to the file handle provided.
1216//----------------------------------------------------------------------
1217void
1218DynamicLoaderMacOSXDYLD::DYLDImageInfo::PutToLog (Log *log) const
1219{
1220    if (log == NULL)
1221        return;
1222    uint8_t *u = (uint8_t *)uuid.GetBytes();
1223
1224    if (address == LLDB_INVALID_ADDRESS)
1225    {
1226        if (u)
1227        {
1228            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)",
1229                        mod_date,
1230                        u[ 0], u[ 1], u[ 2], u[ 3],
1231                        u[ 4], u[ 5], u[ 6], u[ 7],
1232                        u[ 8], u[ 9], u[10], u[11],
1233                        u[12], u[13], u[14], u[15],
1234                        file_spec.GetDirectory().AsCString(),
1235                        file_spec.GetFilename().AsCString());
1236        }
1237        else
1238            log->Printf("\t                           modtime=0x%8.8llx path='%s/%s' (UNLOADED)",
1239                        mod_date,
1240                        file_spec.GetDirectory().AsCString(),
1241                        file_spec.GetFilename().AsCString());
1242    }
1243    else
1244    {
1245        if (u)
1246        {
1247            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'",
1248                        address,
1249                        mod_date,
1250                        u[ 0], u[ 1], u[ 2], u[ 3],
1251                        u[ 4], u[ 5], u[ 6], u[ 7],
1252                        u[ 8], u[ 9], u[10], u[11],
1253                        u[12], u[13], u[14], u[15],
1254                        file_spec.GetDirectory().AsCString(),
1255                        file_spec.GetFilename().AsCString());
1256        }
1257        else
1258        {
1259            log->Printf("\taddress=0x%16.16llx modtime=0x%8.8llx path='%s/%s'",
1260                        address,
1261                        mod_date,
1262                        file_spec.GetDirectory().AsCString(),
1263                        file_spec.GetFilename().AsCString());
1264
1265        }
1266        for (uint32_t i=0; i<segments.size(); ++i)
1267            segments[i].PutToLog(log, slide);
1268    }
1269}
1270
1271//----------------------------------------------------------------------
1272// Dump the _dyld_all_image_infos members and all current image infos
1273// that we have parsed to the file handle provided.
1274//----------------------------------------------------------------------
1275void
1276DynamicLoaderMacOSXDYLD::PutToLog(Log *log) const
1277{
1278    if (log == NULL)
1279        return;
1280
1281    Mutex::Locker locker(m_mutex);
1282    log->Printf("dyld_all_image_infos = { version=%d, count=%d, addr=0x%8.8llx, notify=0x%8.8llx }",
1283                    m_dyld_all_image_infos.version,
1284                    m_dyld_all_image_infos.dylib_info_count,
1285                    (uint64_t)m_dyld_all_image_infos.dylib_info_addr,
1286                    (uint64_t)m_dyld_all_image_infos.notification);
1287    size_t i;
1288    const size_t count = m_dyld_image_infos.size();
1289    if (count > 0)
1290    {
1291        log->PutCString("Loaded:");
1292        for (i = 0; i<count; i++)
1293            m_dyld_image_infos[i].PutToLog(log);
1294    }
1295}
1296
1297void
1298DynamicLoaderMacOSXDYLD::PrivateInitialize(Process *process)
1299{
1300    DEBUG_PRINTF("DynamicLoaderMacOSXDYLD::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState()));
1301    Clear(true);
1302    m_process = process;
1303    m_process->GetTarget().GetSectionLoadList().Clear();
1304}
1305
1306bool
1307DynamicLoaderMacOSXDYLD::SetNotificationBreakpoint ()
1308{
1309    DEBUG_PRINTF("DynamicLoaderMacOSXDYLD::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState()));
1310    if (m_break_id == LLDB_INVALID_BREAK_ID)
1311    {
1312        if (m_dyld_all_image_infos.notification != LLDB_INVALID_ADDRESS)
1313        {
1314            Address so_addr;
1315            // Set the notification breakpoint and install a breakpoint
1316            // callback function that will get called each time the
1317            // breakpoint gets hit. We will use this to track when shared
1318            // libraries get loaded/unloaded.
1319
1320            if (m_process->GetTarget().GetSectionLoadList().ResolveLoadAddress(m_dyld_all_image_infos.notification, so_addr))
1321            {
1322                Breakpoint *dyld_break = m_process->GetTarget().CreateBreakpoint (so_addr, true).get();
1323                dyld_break->SetCallback (DynamicLoaderMacOSXDYLD::NotifyBreakpointHit, this, true);
1324                m_break_id = dyld_break->GetID();
1325            }
1326        }
1327    }
1328    return m_break_id != LLDB_INVALID_BREAK_ID;
1329}
1330
1331//----------------------------------------------------------------------
1332// Member function that gets called when the process state changes.
1333//----------------------------------------------------------------------
1334void
1335DynamicLoaderMacOSXDYLD::PrivateProcessStateChanged (Process *process, StateType state)
1336{
1337    DEBUG_PRINTF("DynamicLoaderMacOSXDYLD::%s(%s)\n", __FUNCTION__, StateAsCString(state));
1338    switch (state)
1339    {
1340    case eStateConnected:
1341    case eStateAttaching:
1342    case eStateLaunching:
1343    case eStateInvalid:
1344    case eStateUnloaded:
1345    case eStateExited:
1346    case eStateDetached:
1347        Clear(false);
1348        break;
1349
1350    case eStateStopped:
1351        // Keep trying find dyld and set our notification breakpoint each time
1352        // we stop until we succeed
1353        if (!DidSetNotificationBreakpoint () && m_process->IsAlive())
1354        {
1355            if (NeedToLocateDYLD ())
1356                LocateDYLD ();
1357
1358            SetNotificationBreakpoint ();
1359        }
1360        break;
1361
1362    case eStateRunning:
1363    case eStateStepping:
1364    case eStateCrashed:
1365    case eStateSuspended:
1366        break;
1367
1368    default:
1369        break;
1370    }
1371}
1372
1373ThreadPlanSP
1374DynamicLoaderMacOSXDYLD::GetStepThroughTrampolinePlan (Thread &thread, bool stop_others)
1375{
1376    ThreadPlanSP thread_plan_sp;
1377    StackFrame *current_frame = thread.GetStackFrameAtIndex(0).get();
1378    const SymbolContext &current_context = current_frame->GetSymbolContext(eSymbolContextSymbol);
1379    Symbol *current_symbol = current_context.symbol;
1380    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1381
1382    if (current_symbol != NULL)
1383    {
1384        if (current_symbol->IsTrampoline())
1385        {
1386            const ConstString &trampoline_name = current_symbol->GetMangled().GetName(Mangled::ePreferMangled);
1387
1388            if (trampoline_name)
1389            {
1390                SymbolContextList target_symbols;
1391                ModuleList &images = thread.GetProcess().GetTarget().GetImages();
1392                images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeCode, target_symbols);
1393                // FIXME - Make the Run to Address take multiple addresses, and
1394                // run to any of them.
1395                uint32_t num_symbols = target_symbols.GetSize();
1396                if (num_symbols == 1)
1397                {
1398                    SymbolContext context;
1399                    AddressRange addr_range;
1400                    if (target_symbols.GetContextAtIndex(0, context))
1401                    {
1402                        context.GetAddressRange (eSymbolContextEverything, 0, false, addr_range);
1403                        thread_plan_sp.reset (new ThreadPlanRunToAddress (thread, addr_range.GetBaseAddress(), stop_others));
1404                    }
1405                    else
1406                    {
1407                        if (log)
1408                            log->Printf ("Couldn't resolve the symbol context.");
1409                    }
1410                }
1411                else if (num_symbols > 1)
1412                {
1413                    std::vector<lldb::addr_t>  addresses;
1414                    addresses.resize (num_symbols);
1415                    for (uint32_t i = 0; i < num_symbols; i++)
1416                    {
1417                        SymbolContext context;
1418                        AddressRange addr_range;
1419                        if (target_symbols.GetContextAtIndex(i, context))
1420                        {
1421                            context.GetAddressRange (eSymbolContextEverything, 0, false, addr_range);
1422                            lldb::addr_t load_addr = addr_range.GetBaseAddress().GetLoadAddress(&thread.GetProcess().GetTarget());
1423                            addresses[i] = load_addr;
1424                        }
1425                    }
1426                    if (addresses.size() > 0)
1427                        thread_plan_sp.reset (new ThreadPlanRunToAddress (thread, addresses, stop_others));
1428                    else
1429                    {
1430                        if (log)
1431                            log->Printf ("Couldn't resolve the symbol contexts.");
1432                    }
1433                }
1434                else
1435                {
1436                    if (log)
1437                    {
1438                        log->Printf ("Could not find symbol for trampoline target: \"%s\"", trampoline_name.AsCString());
1439                    }
1440                }
1441            }
1442        }
1443    }
1444    else
1445    {
1446        if (log)
1447            log->Printf ("Could not find symbol for step through.");
1448    }
1449
1450    return thread_plan_sp;
1451}
1452
1453Error
1454DynamicLoaderMacOSXDYLD::CanLoadImage ()
1455{
1456    Error error;
1457    // In order for us to tell if we can load a shared library we verify that
1458    // the dylib_info_addr isn't zero (which means no shared libraries have
1459    // been set yet, or dyld is currently mucking with the shared library list).
1460    if (ReadAllImageInfosStructure ())
1461    {
1462        // TODO: also check the _dyld_global_lock_held variable in libSystem.B.dylib?
1463        // TODO: check the malloc lock?
1464        // TODO: check the objective C lock?
1465        if (m_dyld_all_image_infos.dylib_info_addr != 0)
1466            return error; // Success
1467    }
1468
1469    error.SetErrorString("unsafe to load or unload shared libraries");
1470    return error;
1471}
1472
1473void
1474DynamicLoaderMacOSXDYLD::Initialize()
1475{
1476    PluginManager::RegisterPlugin (GetPluginNameStatic(),
1477                                   GetPluginDescriptionStatic(),
1478                                   CreateInstance);
1479}
1480
1481void
1482DynamicLoaderMacOSXDYLD::Terminate()
1483{
1484    PluginManager::UnregisterPlugin (CreateInstance);
1485}
1486
1487
1488const char *
1489DynamicLoaderMacOSXDYLD::GetPluginNameStatic()
1490{
1491    return "dynamic-loader.macosx-dyld";
1492}
1493
1494const char *
1495DynamicLoaderMacOSXDYLD::GetPluginDescriptionStatic()
1496{
1497    return "Dynamic loader plug-in that watches for shared library loads/unloads in MacOSX user processes.";
1498}
1499
1500
1501//------------------------------------------------------------------
1502// PluginInterface protocol
1503//------------------------------------------------------------------
1504const char *
1505DynamicLoaderMacOSXDYLD::GetPluginName()
1506{
1507    return "DynamicLoaderMacOSXDYLD";
1508}
1509
1510const char *
1511DynamicLoaderMacOSXDYLD::GetShortPluginName()
1512{
1513    return GetPluginNameStatic();
1514}
1515
1516uint32_t
1517DynamicLoaderMacOSXDYLD::GetPluginVersion()
1518{
1519    return 1;
1520}
1521
1522