Target.cpp revision 22a56cc608f2b7be31b8d889e4f9ce02c649dc45
1//===-- Target.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/Target/Target.h"
11
12// C Includes
13// C++ Includes
14// Other libraries and framework includes
15// Project includes
16#include "lldb/Breakpoint/BreakpointResolver.h"
17#include "lldb/Breakpoint/BreakpointResolverAddress.h"
18#include "lldb/Breakpoint/BreakpointResolverFileLine.h"
19#include "lldb/Breakpoint/BreakpointResolverName.h"
20#include "lldb/Core/Debugger.h"
21#include "lldb/Core/Event.h"
22#include "lldb/Core/Log.h"
23#include "lldb/Core/StreamAsynchronousIO.h"
24#include "lldb/Core/StreamString.h"
25#include "lldb/Core/Timer.h"
26#include "lldb/Core/ValueObject.h"
27#include "lldb/Expression/ClangUserExpression.h"
28#include "lldb/Host/Host.h"
29#include "lldb/Interpreter/CommandInterpreter.h"
30#include "lldb/Interpreter/CommandReturnObject.h"
31#include "lldb/lldb-private-log.h"
32#include "lldb/Symbol/ObjectFile.h"
33#include "lldb/Target/Process.h"
34#include "lldb/Target/StackFrame.h"
35#include "lldb/Target/Thread.h"
36#include "lldb/Target/ThreadSpec.h"
37
38using namespace lldb;
39using namespace lldb_private;
40
41//----------------------------------------------------------------------
42// Target constructor
43//----------------------------------------------------------------------
44Target::Target(Debugger &debugger, const ArchSpec &target_arch, const lldb::PlatformSP &platform_sp) :
45    Broadcaster ("lldb.target"),
46    ExecutionContextScope (),
47    TargetInstanceSettings (*GetSettingsController()),
48    m_debugger (debugger),
49    m_platform_sp (platform_sp),
50    m_mutex (Mutex::eMutexTypeRecursive),
51    m_arch (target_arch),
52    m_images (),
53    m_section_load_list (),
54    m_breakpoint_list (false),
55    m_internal_breakpoint_list (true),
56    m_watchpoint_location_list (),
57    m_process_sp (),
58    m_search_filter_sp (),
59    m_image_search_paths (ImageSearchPathsChanged, this),
60    m_scratch_ast_context_ap (NULL),
61    m_persistent_variables (),
62    m_source_manager(*this),
63    m_stop_hooks (),
64    m_stop_hook_next_id (0),
65    m_suppress_stop_hooks (false)
66{
67    SetEventName (eBroadcastBitBreakpointChanged, "breakpoint-changed");
68    SetEventName (eBroadcastBitModulesLoaded, "modules-loaded");
69    SetEventName (eBroadcastBitModulesUnloaded, "modules-unloaded");
70
71    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
72    if (log)
73        log->Printf ("%p Target::Target()", this);
74}
75
76//----------------------------------------------------------------------
77// Destructor
78//----------------------------------------------------------------------
79Target::~Target()
80{
81    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
82    if (log)
83        log->Printf ("%p Target::~Target()", this);
84    DeleteCurrentProcess ();
85}
86
87void
88Target::Dump (Stream *s, lldb::DescriptionLevel description_level)
89{
90//    s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
91    if (description_level != lldb::eDescriptionLevelBrief)
92    {
93        s->Indent();
94        s->PutCString("Target\n");
95        s->IndentMore();
96            m_images.Dump(s);
97            m_breakpoint_list.Dump(s);
98            m_internal_breakpoint_list.Dump(s);
99        s->IndentLess();
100    }
101    else
102    {
103        Module *exe_module = GetExecutableModulePointer();
104        if (exe_module)
105            s->PutCString (exe_module->GetFileSpec().GetFilename().GetCString());
106        else
107            s->PutCString ("No executable module.");
108    }
109}
110
111void
112Target::DeleteCurrentProcess ()
113{
114    if (m_process_sp.get())
115    {
116        m_section_load_list.Clear();
117        if (m_process_sp->IsAlive())
118            m_process_sp->Destroy();
119
120        m_process_sp->Finalize();
121
122        // Do any cleanup of the target we need to do between process instances.
123        // NB It is better to do this before destroying the process in case the
124        // clean up needs some help from the process.
125        m_breakpoint_list.ClearAllBreakpointSites();
126        m_internal_breakpoint_list.ClearAllBreakpointSites();
127        m_process_sp.reset();
128    }
129}
130
131const lldb::ProcessSP &
132Target::CreateProcess (Listener &listener, const char *plugin_name)
133{
134    DeleteCurrentProcess ();
135    m_process_sp.reset(Process::FindPlugin(*this, plugin_name, listener));
136    return m_process_sp;
137}
138
139const lldb::ProcessSP &
140Target::GetProcessSP () const
141{
142    return m_process_sp;
143}
144
145lldb::TargetSP
146Target::GetSP()
147{
148    return m_debugger.GetTargetList().GetTargetSP(this);
149}
150
151void
152Target::Destroy()
153{
154    Mutex::Locker locker (m_mutex);
155    DeleteCurrentProcess ();
156    m_platform_sp.reset();
157    m_arch.Clear();
158    m_images.Clear();
159    m_section_load_list.Clear();
160    const bool notify = false;
161    m_breakpoint_list.RemoveAll(notify);
162    m_internal_breakpoint_list.RemoveAll(notify);
163    m_last_created_breakpoint.reset();
164    m_search_filter_sp.reset();
165    m_image_search_paths.Clear(notify);
166    m_scratch_ast_context_ap.reset();
167    m_persistent_variables.Clear();
168    m_stop_hooks.clear();
169    m_stop_hook_next_id = 0;
170    m_suppress_stop_hooks = false;
171}
172
173
174BreakpointList &
175Target::GetBreakpointList(bool internal)
176{
177    if (internal)
178        return m_internal_breakpoint_list;
179    else
180        return m_breakpoint_list;
181}
182
183const BreakpointList &
184Target::GetBreakpointList(bool internal) const
185{
186    if (internal)
187        return m_internal_breakpoint_list;
188    else
189        return m_breakpoint_list;
190}
191
192BreakpointSP
193Target::GetBreakpointByID (break_id_t break_id)
194{
195    BreakpointSP bp_sp;
196
197    if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
198        bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
199    else
200        bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
201
202    return bp_sp;
203}
204
205BreakpointSP
206Target::CreateBreakpoint (const FileSpec *containingModule, const FileSpec &file, uint32_t line_no, bool check_inlines, bool internal)
207{
208    SearchFilterSP filter_sp(GetSearchFilterForModule (containingModule));
209    BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine (NULL, file, line_no, check_inlines));
210    return CreateBreakpoint (filter_sp, resolver_sp, internal);
211}
212
213
214BreakpointSP
215Target::CreateBreakpoint (lldb::addr_t addr, bool internal)
216{
217    Address so_addr;
218    // Attempt to resolve our load address if possible, though it is ok if
219    // it doesn't resolve to section/offset.
220
221    // Try and resolve as a load address if possible
222    m_section_load_list.ResolveLoadAddress(addr, so_addr);
223    if (!so_addr.IsValid())
224    {
225        // The address didn't resolve, so just set this as an absolute address
226        so_addr.SetOffset (addr);
227    }
228    BreakpointSP bp_sp (CreateBreakpoint(so_addr, internal));
229    return bp_sp;
230}
231
232BreakpointSP
233Target::CreateBreakpoint (Address &addr, bool internal)
234{
235    TargetSP target_sp = this->GetSP();
236    SearchFilterSP filter_sp(new SearchFilter (target_sp));
237    BreakpointResolverSP resolver_sp (new BreakpointResolverAddress (NULL, addr));
238    return CreateBreakpoint (filter_sp, resolver_sp, internal);
239}
240
241BreakpointSP
242Target::CreateBreakpoint (const FileSpec *containingModule,
243                          const char *func_name,
244                          uint32_t func_name_type_mask,
245                          bool internal,
246                          LazyBool skip_prologue)
247{
248    BreakpointSP bp_sp;
249    if (func_name)
250    {
251        SearchFilterSP filter_sp(GetSearchFilterForModule (containingModule));
252
253        BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL,
254                                                                      func_name,
255                                                                      func_name_type_mask,
256                                                                      Breakpoint::Exact,
257                                                                      skip_prologue == eLazyBoolCalculate ? GetSkipPrologue() : skip_prologue));
258        bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal);
259    }
260    return bp_sp;
261}
262
263
264SearchFilterSP
265Target::GetSearchFilterForModule (const FileSpec *containingModule)
266{
267    SearchFilterSP filter_sp;
268    lldb::TargetSP target_sp = this->GetSP();
269    if (containingModule != NULL)
270    {
271        // TODO: We should look into sharing module based search filters
272        // across many breakpoints like we do for the simple target based one
273        filter_sp.reset (new SearchFilterByModule (target_sp, *containingModule));
274    }
275    else
276    {
277        if (m_search_filter_sp.get() == NULL)
278            m_search_filter_sp.reset (new SearchFilter (target_sp));
279        filter_sp = m_search_filter_sp;
280    }
281    return filter_sp;
282}
283
284BreakpointSP
285Target::CreateBreakpoint (const FileSpec *containingModule,
286                          RegularExpression &func_regex,
287                          bool internal,
288                          LazyBool skip_prologue)
289{
290    SearchFilterSP filter_sp(GetSearchFilterForModule (containingModule));
291    BreakpointResolverSP resolver_sp(new BreakpointResolverName (NULL,
292                                                                 func_regex,
293                                                                 skip_prologue == eLazyBoolCalculate ? GetSkipPrologue() : skip_prologue));
294
295    return CreateBreakpoint (filter_sp, resolver_sp, internal);
296}
297
298BreakpointSP
299Target::CreateBreakpoint (SearchFilterSP &filter_sp, BreakpointResolverSP &resolver_sp, bool internal)
300{
301    BreakpointSP bp_sp;
302    if (filter_sp && resolver_sp)
303    {
304        bp_sp.reset(new Breakpoint (*this, filter_sp, resolver_sp));
305        resolver_sp->SetBreakpoint (bp_sp.get());
306
307        if (internal)
308            m_internal_breakpoint_list.Add (bp_sp, false);
309        else
310            m_breakpoint_list.Add (bp_sp, true);
311
312        LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
313        if (log)
314        {
315            StreamString s;
316            bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
317            log->Printf ("Target::%s (internal = %s) => break_id = %s\n", __FUNCTION__, internal ? "yes" : "no", s.GetData());
318        }
319
320        bp_sp->ResolveBreakpoint();
321    }
322
323    if (!internal && bp_sp)
324    {
325        m_last_created_breakpoint = bp_sp;
326    }
327
328    return bp_sp;
329}
330
331// See also WatchpointLocation::SetWatchpointType(uint32_t type) and
332// the OptionGroupWatchpoint::WatchType enum type.
333WatchpointLocationSP
334Target::CreateWatchpointLocation(lldb::addr_t addr, size_t size, uint32_t type)
335{
336    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
337    if (log)
338        log->Printf("Target::%s (addr = 0x%8.8llx size = %zu type = %u)\n",
339                    __FUNCTION__, addr, size, type);
340
341    WatchpointLocationSP wp_loc_sp;
342    bool process_is_valid = m_process_sp && m_process_sp->IsAlive();
343    if (!process_is_valid)
344        return wp_loc_sp;
345    if (addr == LLDB_INVALID_ADDRESS || size == 0)
346        return wp_loc_sp;
347
348    // Currently we only support one watchpoint location per address, with total
349    // number of watchpoint locations limited by the hardware which the inferior
350    // is running on.
351    WatchpointLocationSP matched_sp = m_watchpoint_location_list.FindByAddress(addr);
352    if (matched_sp)
353    {
354        size_t old_size = matched_sp->GetByteSize();
355        uint32_t old_type =
356            (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) |
357            (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0);
358        // Return the existing watchpoint location if both size and type match.
359        if (size == old_size && type == old_type) {
360            wp_loc_sp = matched_sp;
361            wp_loc_sp->SetEnabled(false);
362        } else {
363            // Nil the matched watchpoint location; we will be creating a new one.
364            m_process_sp->DisableWatchpoint(matched_sp.get());
365            m_watchpoint_location_list.Remove(matched_sp->GetID());
366        }
367    }
368
369    if (!wp_loc_sp) {
370        WatchpointLocation *new_loc = new WatchpointLocation(addr, size);
371        if (!new_loc) {
372            printf("WatchpointLocation ctor failed, out of memory?\n");
373            return wp_loc_sp;
374        }
375        new_loc->SetWatchpointType(type);
376        wp_loc_sp.reset(new_loc);
377        m_watchpoint_location_list.Add(wp_loc_sp);
378    }
379
380    Error rc = m_process_sp->EnableWatchpoint(wp_loc_sp.get());
381    if (log)
382            log->Printf("Target::%s (creation of watchpoint %s with id = %u)\n",
383                        __FUNCTION__,
384                        rc.Success() ? "succeeded" : "failed",
385                        wp_loc_sp->GetID());
386
387    if (rc.Fail()) wp_loc_sp.reset();
388    return wp_loc_sp;
389}
390
391void
392Target::RemoveAllBreakpoints (bool internal_also)
393{
394    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
395    if (log)
396        log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
397
398    m_breakpoint_list.RemoveAll (true);
399    if (internal_also)
400        m_internal_breakpoint_list.RemoveAll (false);
401
402    m_last_created_breakpoint.reset();
403}
404
405void
406Target::DisableAllBreakpoints (bool internal_also)
407{
408    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
409    if (log)
410        log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
411
412    m_breakpoint_list.SetEnabledAll (false);
413    if (internal_also)
414        m_internal_breakpoint_list.SetEnabledAll (false);
415}
416
417void
418Target::EnableAllBreakpoints (bool internal_also)
419{
420    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
421    if (log)
422        log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
423
424    m_breakpoint_list.SetEnabledAll (true);
425    if (internal_also)
426        m_internal_breakpoint_list.SetEnabledAll (true);
427}
428
429bool
430Target::RemoveBreakpointByID (break_id_t break_id)
431{
432    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
433    if (log)
434        log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
435
436    if (DisableBreakpointByID (break_id))
437    {
438        if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
439            m_internal_breakpoint_list.Remove(break_id, false);
440        else
441        {
442            if (m_last_created_breakpoint)
443            {
444                if (m_last_created_breakpoint->GetID() == break_id)
445                    m_last_created_breakpoint.reset();
446            }
447            m_breakpoint_list.Remove(break_id, true);
448        }
449        return true;
450    }
451    return false;
452}
453
454bool
455Target::DisableBreakpointByID (break_id_t break_id)
456{
457    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
458    if (log)
459        log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
460
461    BreakpointSP bp_sp;
462
463    if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
464        bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
465    else
466        bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
467    if (bp_sp)
468    {
469        bp_sp->SetEnabled (false);
470        return true;
471    }
472    return false;
473}
474
475bool
476Target::EnableBreakpointByID (break_id_t break_id)
477{
478    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
479    if (log)
480        log->Printf ("Target::%s (break_id = %i, internal = %s)\n",
481                     __FUNCTION__,
482                     break_id,
483                     LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
484
485    BreakpointSP bp_sp;
486
487    if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
488        bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
489    else
490        bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
491
492    if (bp_sp)
493    {
494        bp_sp->SetEnabled (true);
495        return true;
496    }
497    return false;
498}
499
500ModuleSP
501Target::GetExecutableModule ()
502{
503    return m_images.GetModuleAtIndex(0);
504}
505
506Module*
507Target::GetExecutableModulePointer ()
508{
509    return m_images.GetModulePointerAtIndex(0);
510}
511
512void
513Target::SetExecutableModule (ModuleSP& executable_sp, bool get_dependent_files)
514{
515    m_images.Clear();
516    m_scratch_ast_context_ap.reset();
517
518    if (executable_sp.get())
519    {
520        Timer scoped_timer (__PRETTY_FUNCTION__,
521                            "Target::SetExecutableModule (executable = '%s/%s')",
522                            executable_sp->GetFileSpec().GetDirectory().AsCString(),
523                            executable_sp->GetFileSpec().GetFilename().AsCString());
524
525        m_images.Append(executable_sp); // The first image is our exectuable file
526
527        // If we haven't set an architecture yet, reset our architecture based on what we found in the executable module.
528        if (!m_arch.IsValid())
529            m_arch = executable_sp->GetArchitecture();
530
531        FileSpecList dependent_files;
532        ObjectFile *executable_objfile = executable_sp->GetObjectFile();
533        // Let's find the file & line for main and set the default source file from there.
534        if (!m_source_manager.DefaultFileAndLineSet())
535        {
536            SymbolContextList sc_list;
537            uint32_t num_matches;
538            ConstString main_name("main");
539            bool symbols_okay = false;  // Force it to be a debug symbol.
540            bool append = false;
541            num_matches = executable_sp->FindFunctions (main_name, eFunctionNameTypeBase, symbols_okay, append, sc_list);
542            for (uint32_t idx = 0; idx < num_matches; idx++)
543            {
544                SymbolContext sc;
545                sc_list.GetContextAtIndex(idx, sc);
546                if (sc.line_entry.file)
547                {
548                    m_source_manager.SetDefaultFileAndLine(sc.line_entry.file, sc.line_entry.line);
549                    break;
550                }
551            }
552        }
553
554        if (executable_objfile)
555        {
556            executable_objfile->GetDependentModules(dependent_files);
557            for (uint32_t i=0; i<dependent_files.GetSize(); i++)
558            {
559                FileSpec dependent_file_spec (dependent_files.GetFileSpecPointerAtIndex(i));
560                FileSpec platform_dependent_file_spec;
561                if (m_platform_sp)
562                    m_platform_sp->GetFile (dependent_file_spec, NULL, platform_dependent_file_spec);
563                else
564                    platform_dependent_file_spec = dependent_file_spec;
565
566                ModuleSP image_module_sp(GetSharedModule (platform_dependent_file_spec,
567                                                          m_arch));
568                if (image_module_sp.get())
569                {
570                    ObjectFile *objfile = image_module_sp->GetObjectFile();
571                    if (objfile)
572                        objfile->GetDependentModules(dependent_files);
573                }
574            }
575        }
576
577    }
578
579    UpdateInstanceName();
580}
581
582
583bool
584Target::SetArchitecture (const ArchSpec &arch_spec)
585{
586    if (m_arch == arch_spec)
587    {
588        // If we're setting the architecture to our current architecture, we
589        // don't need to do anything.
590        return true;
591    }
592    else if (!m_arch.IsValid())
593    {
594        // If we haven't got a valid arch spec, then we just need to set it.
595        m_arch = arch_spec;
596        return true;
597    }
598    else
599    {
600        // If we have an executable file, try to reset the executable to the desired architecture
601        m_arch = arch_spec;
602        ModuleSP executable_sp = GetExecutableModule ();
603        m_images.Clear();
604        m_scratch_ast_context_ap.reset();
605        // Need to do something about unsetting breakpoints.
606
607        if (executable_sp)
608        {
609            FileSpec exec_file_spec = executable_sp->GetFileSpec();
610            Error error = ModuleList::GetSharedModule(exec_file_spec,
611                                                      arch_spec,
612                                                      NULL,
613                                                      NULL,
614                                                      0,
615                                                      executable_sp,
616                                                      NULL,
617                                                      NULL);
618
619            if (!error.Fail() && executable_sp)
620            {
621                SetExecutableModule (executable_sp, true);
622                return true;
623            }
624            else
625            {
626                return false;
627            }
628        }
629        else
630        {
631            return false;
632        }
633    }
634}
635
636void
637Target::ModuleAdded (ModuleSP &module_sp)
638{
639    // A module is being added to this target for the first time
640    ModuleList module_list;
641    module_list.Append(module_sp);
642    ModulesDidLoad (module_list);
643}
644
645void
646Target::ModuleUpdated (ModuleSP &old_module_sp, ModuleSP &new_module_sp)
647{
648    // A module is replacing an already added module
649    ModuleList module_list;
650    module_list.Append (old_module_sp);
651    ModulesDidUnload (module_list);
652    module_list.Clear ();
653    module_list.Append (new_module_sp);
654    ModulesDidLoad (module_list);
655}
656
657void
658Target::ModulesDidLoad (ModuleList &module_list)
659{
660    m_breakpoint_list.UpdateBreakpoints (module_list, true);
661    // TODO: make event data that packages up the module_list
662    BroadcastEvent (eBroadcastBitModulesLoaded, NULL);
663}
664
665void
666Target::ModulesDidUnload (ModuleList &module_list)
667{
668    m_breakpoint_list.UpdateBreakpoints (module_list, false);
669
670    // Remove the images from the target image list
671    m_images.Remove(module_list);
672
673    // TODO: make event data that packages up the module_list
674    BroadcastEvent (eBroadcastBitModulesUnloaded, NULL);
675}
676
677size_t
678Target::ReadMemoryFromFileCache (const Address& addr, void *dst, size_t dst_len, Error &error)
679{
680    const Section *section = addr.GetSection();
681    if (section && section->GetModule())
682    {
683        ObjectFile *objfile = section->GetModule()->GetObjectFile();
684        if (objfile)
685        {
686            size_t bytes_read = section->ReadSectionDataFromObjectFile (objfile,
687                                                                        addr.GetOffset(),
688                                                                        dst,
689                                                                        dst_len);
690            if (bytes_read > 0)
691                return bytes_read;
692            else
693                error.SetErrorStringWithFormat("error reading data from section %s", section->GetName().GetCString());
694        }
695        else
696        {
697            error.SetErrorString("address isn't from a object file");
698        }
699    }
700    else
701    {
702        error.SetErrorString("address doesn't contain a section that points to a section in a object file");
703    }
704    return 0;
705}
706
707size_t
708Target::ReadMemory (const Address& addr,
709                    bool prefer_file_cache,
710                    void *dst,
711                    size_t dst_len,
712                    Error &error,
713                    lldb::addr_t *load_addr_ptr)
714{
715    error.Clear();
716
717    // if we end up reading this from process memory, we will fill this
718    // with the actual load address
719    if (load_addr_ptr)
720        *load_addr_ptr = LLDB_INVALID_ADDRESS;
721
722    bool process_is_valid = m_process_sp && m_process_sp->IsAlive();
723
724    size_t bytes_read = 0;
725
726    addr_t load_addr = LLDB_INVALID_ADDRESS;
727    addr_t file_addr = LLDB_INVALID_ADDRESS;
728    Address resolved_addr;
729    if (!addr.IsSectionOffset())
730    {
731        if (m_section_load_list.IsEmpty())
732        {
733            // No sections are loaded, so we must assume we are not running
734            // yet and anything we are given is a file address.
735            file_addr = addr.GetOffset(); // "addr" doesn't have a section, so its offset is the file address
736            m_images.ResolveFileAddress (file_addr, resolved_addr);
737        }
738        else
739        {
740            // We have at least one section loaded. This can be becuase
741            // we have manually loaded some sections with "target modules load ..."
742            // or because we have have a live process that has sections loaded
743            // through the dynamic loader
744            load_addr = addr.GetOffset(); // "addr" doesn't have a section, so its offset is the load address
745            m_section_load_list.ResolveLoadAddress (load_addr, resolved_addr);
746        }
747    }
748    if (!resolved_addr.IsValid())
749        resolved_addr = addr;
750
751
752    if (prefer_file_cache)
753    {
754        bytes_read = ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error);
755        if (bytes_read > 0)
756            return bytes_read;
757    }
758
759    if (process_is_valid)
760    {
761        if (load_addr == LLDB_INVALID_ADDRESS)
762            load_addr = resolved_addr.GetLoadAddress (this);
763
764        if (load_addr == LLDB_INVALID_ADDRESS)
765        {
766            if (resolved_addr.GetModule() && resolved_addr.GetModule()->GetFileSpec())
767                error.SetErrorStringWithFormat("%s[0x%llx] can't be resolved, %s in not currently loaded.\n",
768                                               resolved_addr.GetModule()->GetFileSpec().GetFilename().AsCString(),
769                                               resolved_addr.GetFileAddress());
770            else
771                error.SetErrorStringWithFormat("0x%llx can't be resolved.\n", resolved_addr.GetFileAddress());
772        }
773        else
774        {
775            bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
776            if (bytes_read != dst_len)
777            {
778                if (error.Success())
779                {
780                    if (bytes_read == 0)
781                        error.SetErrorStringWithFormat("Read memory from 0x%llx failed.\n", load_addr);
782                    else
783                        error.SetErrorStringWithFormat("Only %zu of %zu bytes were read from memory at 0x%llx.\n", bytes_read, dst_len, load_addr);
784                }
785            }
786            if (bytes_read)
787            {
788                if (load_addr_ptr)
789                    *load_addr_ptr = load_addr;
790                return bytes_read;
791            }
792            // If the address is not section offset we have an address that
793            // doesn't resolve to any address in any currently loaded shared
794            // libaries and we failed to read memory so there isn't anything
795            // more we can do. If it is section offset, we might be able to
796            // read cached memory from the object file.
797            if (!resolved_addr.IsSectionOffset())
798                return 0;
799        }
800    }
801
802    if (!prefer_file_cache && resolved_addr.IsSectionOffset())
803    {
804        // If we didn't already try and read from the object file cache, then
805        // try it after failing to read from the process.
806        return ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error);
807    }
808    return 0;
809}
810
811size_t
812Target::ReadScalarIntegerFromMemory (const Address& addr,
813                                     bool prefer_file_cache,
814                                     uint32_t byte_size,
815                                     bool is_signed,
816                                     Scalar &scalar,
817                                     Error &error)
818{
819    uint64_t uval;
820
821    if (byte_size <= sizeof(uval))
822    {
823        size_t bytes_read = ReadMemory (addr, prefer_file_cache, &uval, byte_size, error);
824        if (bytes_read == byte_size)
825        {
826            DataExtractor data (&uval, sizeof(uval), m_arch.GetByteOrder(), m_arch.GetAddressByteSize());
827            uint32_t offset = 0;
828            if (byte_size <= 4)
829                scalar = data.GetMaxU32 (&offset, byte_size);
830            else
831                scalar = data.GetMaxU64 (&offset, byte_size);
832
833            if (is_signed)
834                scalar.SignExtend(byte_size * 8);
835            return bytes_read;
836        }
837    }
838    else
839    {
840        error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
841    }
842    return 0;
843}
844
845uint64_t
846Target::ReadUnsignedIntegerFromMemory (const Address& addr,
847                                       bool prefer_file_cache,
848                                       size_t integer_byte_size,
849                                       uint64_t fail_value,
850                                       Error &error)
851{
852    Scalar scalar;
853    if (ReadScalarIntegerFromMemory (addr,
854                                     prefer_file_cache,
855                                     integer_byte_size,
856                                     false,
857                                     scalar,
858                                     error))
859        return scalar.ULongLong(fail_value);
860    return fail_value;
861}
862
863bool
864Target::ReadPointerFromMemory (const Address& addr,
865                               bool prefer_file_cache,
866                               Error &error,
867                               Address &pointer_addr)
868{
869    Scalar scalar;
870    if (ReadScalarIntegerFromMemory (addr,
871                                     prefer_file_cache,
872                                     m_arch.GetAddressByteSize(),
873                                     false,
874                                     scalar,
875                                     error))
876    {
877        addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
878        if (pointer_vm_addr != LLDB_INVALID_ADDRESS)
879        {
880            if (m_section_load_list.IsEmpty())
881            {
882                // No sections are loaded, so we must assume we are not running
883                // yet and anything we are given is a file address.
884                m_images.ResolveFileAddress (pointer_vm_addr, pointer_addr);
885            }
886            else
887            {
888                // We have at least one section loaded. This can be becuase
889                // we have manually loaded some sections with "target modules load ..."
890                // or because we have have a live process that has sections loaded
891                // through the dynamic loader
892                m_section_load_list.ResolveLoadAddress (pointer_vm_addr, pointer_addr);
893            }
894            // We weren't able to resolve the pointer value, so just return
895            // an address with no section
896            if (!pointer_addr.IsValid())
897                pointer_addr.SetOffset (pointer_vm_addr);
898            return true;
899
900        }
901    }
902    return false;
903}
904
905ModuleSP
906Target::GetSharedModule
907(
908    const FileSpec& file_spec,
909    const ArchSpec& arch,
910    const lldb_private::UUID *uuid_ptr,
911    const ConstString *object_name,
912    off_t object_offset,
913    Error *error_ptr
914)
915{
916    // Don't pass in the UUID so we can tell if we have a stale value in our list
917    ModuleSP old_module_sp; // This will get filled in if we have a new version of the library
918    bool did_create_module = false;
919    ModuleSP module_sp;
920
921    Error error;
922
923    // If there are image search path entries, try to use them first to acquire a suitable image.
924    if (m_image_search_paths.GetSize())
925    {
926        FileSpec transformed_spec;
927        if (m_image_search_paths.RemapPath (file_spec.GetDirectory(), transformed_spec.GetDirectory()))
928        {
929            transformed_spec.GetFilename() = file_spec.GetFilename();
930            error = ModuleList::GetSharedModule (transformed_spec, arch, uuid_ptr, object_name, object_offset, module_sp, &old_module_sp, &did_create_module);
931        }
932    }
933
934    // The platform is responsible for finding and caching an appropriate
935    // module in the shared module cache.
936    if (m_platform_sp)
937    {
938        FileSpec platform_file_spec;
939        error = m_platform_sp->GetSharedModule (file_spec,
940                                                arch,
941                                                uuid_ptr,
942                                                object_name,
943                                                object_offset,
944                                                module_sp,
945                                                &old_module_sp,
946                                                &did_create_module);
947    }
948    else
949    {
950        error.SetErrorString("no platform is currently set");
951    }
952
953    // If a module hasn't been found yet, use the unmodified path.
954    if (module_sp)
955    {
956        m_images.Append (module_sp);
957        if (did_create_module)
958        {
959            if (old_module_sp && m_images.GetIndexForModule (old_module_sp.get()) != LLDB_INVALID_INDEX32)
960                ModuleUpdated(old_module_sp, module_sp);
961            else
962                ModuleAdded(module_sp);
963        }
964    }
965    if (error_ptr)
966        *error_ptr = error;
967    return module_sp;
968}
969
970
971Target *
972Target::CalculateTarget ()
973{
974    return this;
975}
976
977Process *
978Target::CalculateProcess ()
979{
980    return NULL;
981}
982
983Thread *
984Target::CalculateThread ()
985{
986    return NULL;
987}
988
989StackFrame *
990Target::CalculateStackFrame ()
991{
992    return NULL;
993}
994
995void
996Target::CalculateExecutionContext (ExecutionContext &exe_ctx)
997{
998    exe_ctx.target = this;
999    exe_ctx.process = NULL; // Do NOT fill in process...
1000    exe_ctx.thread = NULL;
1001    exe_ctx.frame = NULL;
1002}
1003
1004PathMappingList &
1005Target::GetImageSearchPathList ()
1006{
1007    return m_image_search_paths;
1008}
1009
1010void
1011Target::ImageSearchPathsChanged
1012(
1013    const PathMappingList &path_list,
1014    void *baton
1015)
1016{
1017    Target *target = (Target *)baton;
1018    ModuleSP exe_module_sp (target->GetExecutableModule());
1019    if (exe_module_sp)
1020    {
1021        target->m_images.Clear();
1022        target->SetExecutableModule (exe_module_sp, true);
1023    }
1024}
1025
1026ClangASTContext *
1027Target::GetScratchClangASTContext()
1028{
1029    // Now see if we know the target triple, and if so, create our scratch AST context:
1030    if (m_scratch_ast_context_ap.get() == NULL && m_arch.IsValid())
1031        m_scratch_ast_context_ap.reset (new ClangASTContext(m_arch.GetTriple().str().c_str()));
1032    return m_scratch_ast_context_ap.get();
1033}
1034
1035void
1036Target::SettingsInitialize ()
1037{
1038    UserSettingsControllerSP &usc = GetSettingsController();
1039    usc.reset (new SettingsController);
1040    UserSettingsController::InitializeSettingsController (usc,
1041                                                          SettingsController::global_settings_table,
1042                                                          SettingsController::instance_settings_table);
1043
1044    // Now call SettingsInitialize() on each 'child' setting of Target
1045    Process::SettingsInitialize ();
1046}
1047
1048void
1049Target::SettingsTerminate ()
1050{
1051
1052    // Must call SettingsTerminate() on each settings 'child' of Target, before terminating Target's Settings.
1053
1054    Process::SettingsTerminate ();
1055
1056    // Now terminate Target Settings.
1057
1058    UserSettingsControllerSP &usc = GetSettingsController();
1059    UserSettingsController::FinalizeSettingsController (usc);
1060    usc.reset();
1061}
1062
1063UserSettingsControllerSP &
1064Target::GetSettingsController ()
1065{
1066    static UserSettingsControllerSP g_settings_controller;
1067    return g_settings_controller;
1068}
1069
1070ArchSpec
1071Target::GetDefaultArchitecture ()
1072{
1073    lldb::UserSettingsControllerSP settings_controller_sp (GetSettingsController());
1074
1075    if (settings_controller_sp)
1076        return static_cast<Target::SettingsController *>(settings_controller_sp.get())->GetArchitecture ();
1077    return ArchSpec();
1078}
1079
1080void
1081Target::SetDefaultArchitecture (const ArchSpec& arch)
1082{
1083    lldb::UserSettingsControllerSP settings_controller_sp (GetSettingsController());
1084
1085    if (settings_controller_sp)
1086        static_cast<Target::SettingsController *>(settings_controller_sp.get())->GetArchitecture () = arch;
1087}
1088
1089Target *
1090Target::GetTargetFromContexts (const ExecutionContext *exe_ctx_ptr, const SymbolContext *sc_ptr)
1091{
1092    // The target can either exist in the "process" of ExecutionContext, or in
1093    // the "target_sp" member of SymbolContext. This accessor helper function
1094    // will get the target from one of these locations.
1095
1096    Target *target = NULL;
1097    if (sc_ptr != NULL)
1098        target = sc_ptr->target_sp.get();
1099    if (target == NULL)
1100    {
1101        if (exe_ctx_ptr != NULL && exe_ctx_ptr->process != NULL)
1102            target = &exe_ctx_ptr->process->GetTarget();
1103    }
1104    return target;
1105}
1106
1107
1108void
1109Target::UpdateInstanceName ()
1110{
1111    StreamString sstr;
1112
1113    Module *exe_module = GetExecutableModulePointer();
1114    if (exe_module)
1115    {
1116        sstr.Printf ("%s_%s",
1117                     exe_module->GetFileSpec().GetFilename().AsCString(),
1118                     exe_module->GetArchitecture().GetArchitectureName());
1119        GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(), sstr.GetData());
1120    }
1121}
1122
1123const char *
1124Target::GetExpressionPrefixContentsAsCString ()
1125{
1126    if (m_expr_prefix_contents_sp)
1127        return (const char *)m_expr_prefix_contents_sp->GetBytes();
1128    return NULL;
1129}
1130
1131ExecutionResults
1132Target::EvaluateExpression
1133(
1134    const char *expr_cstr,
1135    StackFrame *frame,
1136    bool unwind_on_error,
1137    bool keep_in_memory,
1138    lldb::DynamicValueType use_dynamic,
1139    lldb::ValueObjectSP &result_valobj_sp
1140)
1141{
1142    ExecutionResults execution_results = eExecutionSetupError;
1143
1144    result_valobj_sp.reset();
1145
1146    // We shouldn't run stop hooks in expressions.
1147    // Be sure to reset this if you return anywhere within this function.
1148    bool old_suppress_value = m_suppress_stop_hooks;
1149    m_suppress_stop_hooks = true;
1150
1151    ExecutionContext exe_ctx;
1152    if (frame)
1153    {
1154        frame->CalculateExecutionContext(exe_ctx);
1155        Error error;
1156        const uint32_t expr_path_options = StackFrame::eExpressionPathOptionCheckPtrVsMember |
1157                                           StackFrame::eExpressionPathOptionsNoFragileObjcIvar |
1158                                           StackFrame::eExpressionPathOptionsNoSyntheticChildren;
1159        lldb::VariableSP var_sp;
1160        result_valobj_sp = frame->GetValueForVariableExpressionPath (expr_cstr,
1161                                                                     use_dynamic,
1162                                                                     expr_path_options,
1163                                                                     var_sp,
1164                                                                     error);
1165    }
1166    else if (m_process_sp)
1167    {
1168        m_process_sp->CalculateExecutionContext(exe_ctx);
1169    }
1170    else
1171    {
1172        CalculateExecutionContext(exe_ctx);
1173    }
1174
1175    if (result_valobj_sp)
1176    {
1177        execution_results = eExecutionCompleted;
1178        // We got a result from the frame variable expression path above...
1179        ConstString persistent_variable_name (m_persistent_variables.GetNextPersistentVariableName());
1180
1181        lldb::ValueObjectSP const_valobj_sp;
1182
1183        // Check in case our value is already a constant value
1184        if (result_valobj_sp->GetIsConstant())
1185        {
1186            const_valobj_sp = result_valobj_sp;
1187            const_valobj_sp->SetName (persistent_variable_name);
1188        }
1189        else
1190        {
1191            if (use_dynamic != lldb::eNoDynamicValues)
1192            {
1193                ValueObjectSP dynamic_sp = result_valobj_sp->GetDynamicValue(use_dynamic);
1194                if (dynamic_sp)
1195                    result_valobj_sp = dynamic_sp;
1196            }
1197
1198            const_valobj_sp = result_valobj_sp->CreateConstantValue (persistent_variable_name);
1199        }
1200
1201        lldb::ValueObjectSP live_valobj_sp = result_valobj_sp;
1202
1203        result_valobj_sp = const_valobj_sp;
1204
1205        ClangExpressionVariableSP clang_expr_variable_sp(m_persistent_variables.CreatePersistentVariable(result_valobj_sp));
1206        assert (clang_expr_variable_sp.get());
1207
1208        // Set flags and live data as appropriate
1209
1210        const Value &result_value = live_valobj_sp->GetValue();
1211
1212        switch (result_value.GetValueType())
1213        {
1214        case Value::eValueTypeHostAddress:
1215        case Value::eValueTypeFileAddress:
1216            // we don't do anything with these for now
1217            break;
1218        case Value::eValueTypeScalar:
1219            clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVIsLLDBAllocated;
1220            clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVNeedsAllocation;
1221            break;
1222        case Value::eValueTypeLoadAddress:
1223            clang_expr_variable_sp->m_live_sp = live_valobj_sp;
1224            clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVIsProgramReference;
1225            break;
1226        }
1227    }
1228    else
1229    {
1230        // Make sure we aren't just trying to see the value of a persistent
1231        // variable (something like "$0")
1232        lldb::ClangExpressionVariableSP persistent_var_sp;
1233        // Only check for persistent variables the expression starts with a '$'
1234        if (expr_cstr[0] == '$')
1235            persistent_var_sp = m_persistent_variables.GetVariable (expr_cstr);
1236
1237        if (persistent_var_sp)
1238        {
1239            result_valobj_sp = persistent_var_sp->GetValueObject ();
1240            execution_results = eExecutionCompleted;
1241        }
1242        else
1243        {
1244            const char *prefix = GetExpressionPrefixContentsAsCString();
1245
1246            execution_results = ClangUserExpression::Evaluate (exe_ctx,
1247                                                               unwind_on_error,
1248                                                               expr_cstr,
1249                                                               prefix,
1250                                                               result_valobj_sp);
1251        }
1252    }
1253
1254    m_suppress_stop_hooks = old_suppress_value;
1255
1256    return execution_results;
1257}
1258
1259lldb::addr_t
1260Target::GetCallableLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
1261{
1262    addr_t code_addr = load_addr;
1263    switch (m_arch.GetMachine())
1264    {
1265    case llvm::Triple::arm:
1266    case llvm::Triple::thumb:
1267        switch (addr_class)
1268        {
1269        case eAddressClassData:
1270        case eAddressClassDebug:
1271            return LLDB_INVALID_ADDRESS;
1272
1273        case eAddressClassUnknown:
1274        case eAddressClassInvalid:
1275        case eAddressClassCode:
1276        case eAddressClassCodeAlternateISA:
1277        case eAddressClassRuntime:
1278            // Check if bit zero it no set?
1279            if ((code_addr & 1ull) == 0)
1280            {
1281                // Bit zero isn't set, check if the address is a multiple of 2?
1282                if (code_addr & 2ull)
1283                {
1284                    // The address is a multiple of 2 so it must be thumb, set bit zero
1285                    code_addr |= 1ull;
1286                }
1287                else if (addr_class == eAddressClassCodeAlternateISA)
1288                {
1289                    // We checked the address and the address claims to be the alternate ISA
1290                    // which means thumb, so set bit zero.
1291                    code_addr |= 1ull;
1292                }
1293            }
1294            break;
1295        }
1296        break;
1297
1298    default:
1299        break;
1300    }
1301    return code_addr;
1302}
1303
1304lldb::addr_t
1305Target::GetOpcodeLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
1306{
1307    addr_t opcode_addr = load_addr;
1308    switch (m_arch.GetMachine())
1309    {
1310    case llvm::Triple::arm:
1311    case llvm::Triple::thumb:
1312        switch (addr_class)
1313        {
1314        case eAddressClassData:
1315        case eAddressClassDebug:
1316            return LLDB_INVALID_ADDRESS;
1317
1318        case eAddressClassInvalid:
1319        case eAddressClassUnknown:
1320        case eAddressClassCode:
1321        case eAddressClassCodeAlternateISA:
1322        case eAddressClassRuntime:
1323            opcode_addr &= ~(1ull);
1324            break;
1325        }
1326        break;
1327
1328    default:
1329        break;
1330    }
1331    return opcode_addr;
1332}
1333
1334lldb::user_id_t
1335Target::AddStopHook (Target::StopHookSP &new_hook_sp)
1336{
1337    lldb::user_id_t new_uid = ++m_stop_hook_next_id;
1338    new_hook_sp.reset (new StopHook(GetSP(), new_uid));
1339    m_stop_hooks[new_uid] = new_hook_sp;
1340    return new_uid;
1341}
1342
1343bool
1344Target::RemoveStopHookByID (lldb::user_id_t user_id)
1345{
1346    size_t num_removed;
1347    num_removed = m_stop_hooks.erase (user_id);
1348    if (num_removed == 0)
1349        return false;
1350    else
1351        return true;
1352}
1353
1354void
1355Target::RemoveAllStopHooks ()
1356{
1357    m_stop_hooks.clear();
1358}
1359
1360Target::StopHookSP
1361Target::GetStopHookByID (lldb::user_id_t user_id)
1362{
1363    StopHookSP found_hook;
1364
1365    StopHookCollection::iterator specified_hook_iter;
1366    specified_hook_iter = m_stop_hooks.find (user_id);
1367    if (specified_hook_iter != m_stop_hooks.end())
1368        found_hook = (*specified_hook_iter).second;
1369    return found_hook;
1370}
1371
1372bool
1373Target::SetStopHookActiveStateByID (lldb::user_id_t user_id, bool active_state)
1374{
1375    StopHookCollection::iterator specified_hook_iter;
1376    specified_hook_iter = m_stop_hooks.find (user_id);
1377    if (specified_hook_iter == m_stop_hooks.end())
1378        return false;
1379
1380    (*specified_hook_iter).second->SetIsActive (active_state);
1381    return true;
1382}
1383
1384void
1385Target::SetAllStopHooksActiveState (bool active_state)
1386{
1387    StopHookCollection::iterator pos, end = m_stop_hooks.end();
1388    for (pos = m_stop_hooks.begin(); pos != end; pos++)
1389    {
1390        (*pos).second->SetIsActive (active_state);
1391    }
1392}
1393
1394void
1395Target::RunStopHooks ()
1396{
1397    if (m_suppress_stop_hooks)
1398        return;
1399
1400    if (!m_process_sp)
1401        return;
1402
1403    if (m_stop_hooks.empty())
1404        return;
1405
1406    StopHookCollection::iterator pos, end = m_stop_hooks.end();
1407
1408    // If there aren't any active stop hooks, don't bother either:
1409    bool any_active_hooks = false;
1410    for (pos = m_stop_hooks.begin(); pos != end; pos++)
1411    {
1412        if ((*pos).second->IsActive())
1413        {
1414            any_active_hooks = true;
1415            break;
1416        }
1417    }
1418    if (!any_active_hooks)
1419        return;
1420
1421    CommandReturnObject result;
1422
1423    std::vector<ExecutionContext> exc_ctx_with_reasons;
1424    std::vector<SymbolContext> sym_ctx_with_reasons;
1425
1426    ThreadList &cur_threadlist = m_process_sp->GetThreadList();
1427    size_t num_threads = cur_threadlist.GetSize();
1428    for (size_t i = 0; i < num_threads; i++)
1429    {
1430        lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex (i);
1431        if (cur_thread_sp->ThreadStoppedForAReason())
1432        {
1433            lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
1434            exc_ctx_with_reasons.push_back(ExecutionContext(m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
1435            sym_ctx_with_reasons.push_back(cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
1436        }
1437    }
1438
1439    // If no threads stopped for a reason, don't run the stop-hooks.
1440    size_t num_exe_ctx = exc_ctx_with_reasons.size();
1441    if (num_exe_ctx == 0)
1442        return;
1443
1444    result.SetImmediateOutputStream (m_debugger.GetAsyncOutputStream());
1445    result.SetImmediateErrorStream (m_debugger.GetAsyncErrorStream());
1446
1447    bool keep_going = true;
1448    bool hooks_ran = false;
1449    bool print_hook_header;
1450    bool print_thread_header;
1451
1452    if (num_exe_ctx == 1)
1453        print_thread_header = false;
1454    else
1455        print_thread_header = true;
1456
1457    if (m_stop_hooks.size() == 1)
1458        print_hook_header = false;
1459    else
1460        print_hook_header = true;
1461
1462    for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++)
1463    {
1464        // result.Clear();
1465        StopHookSP cur_hook_sp = (*pos).second;
1466        if (!cur_hook_sp->IsActive())
1467            continue;
1468
1469        bool any_thread_matched = false;
1470        for (size_t i = 0; keep_going && i < num_exe_ctx; i++)
1471        {
1472            if ((cur_hook_sp->GetSpecifier () == NULL
1473                  || cur_hook_sp->GetSpecifier()->SymbolContextMatches(sym_ctx_with_reasons[i]))
1474                && (cur_hook_sp->GetThreadSpecifier() == NULL
1475                    || cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx_with_reasons[i].thread)))
1476            {
1477                if (!hooks_ran)
1478                {
1479                    result.AppendMessage("\n** Stop Hooks **");
1480                    hooks_ran = true;
1481                }
1482                if (print_hook_header && !any_thread_matched)
1483                {
1484                    result.AppendMessageWithFormat("\n- Hook %d\n", cur_hook_sp->GetID());
1485                    any_thread_matched = true;
1486                }
1487
1488                if (print_thread_header)
1489                    result.AppendMessageWithFormat("-- Thread %d\n", exc_ctx_with_reasons[i].thread->GetIndexID());
1490
1491                bool stop_on_continue = true;
1492                bool stop_on_error = true;
1493                bool echo_commands = false;
1494                bool print_results = true;
1495                GetDebugger().GetCommandInterpreter().HandleCommands (cur_hook_sp->GetCommands(),
1496                                                                      &exc_ctx_with_reasons[i],
1497                                                                      stop_on_continue,
1498                                                                      stop_on_error,
1499                                                                      echo_commands,
1500                                                                      print_results,
1501                                                                      result);
1502
1503                // If the command started the target going again, we should bag out of
1504                // running the stop hooks.
1505                if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
1506                    (result.GetStatus() == eReturnStatusSuccessContinuingResult))
1507                {
1508                    result.AppendMessageWithFormat ("Aborting stop hooks, hook %d set the program running.", cur_hook_sp->GetID());
1509                    keep_going = false;
1510                }
1511            }
1512        }
1513    }
1514    if (hooks_ran)
1515        result.AppendMessage ("\n** End Stop Hooks **\n");
1516
1517    result.GetImmediateOutputStream()->Flush();
1518    result.GetImmediateErrorStream()->Flush();
1519}
1520
1521bool
1522Target::LoadModuleWithSlide (Module *module, lldb::addr_t slide)
1523{
1524    bool changed = false;
1525    if (module)
1526    {
1527        ObjectFile *object_file = module->GetObjectFile();
1528        if (object_file)
1529        {
1530            SectionList *section_list = object_file->GetSectionList ();
1531            if (section_list)
1532            {
1533                // All sections listed in the dyld image info structure will all
1534                // either be fixed up already, or they will all be off by a single
1535                // slide amount that is determined by finding the first segment
1536                // that is at file offset zero which also has bytes (a file size
1537                // that is greater than zero) in the object file.
1538
1539                // Determine the slide amount (if any)
1540                const size_t num_sections = section_list->GetSize();
1541                size_t sect_idx = 0;
1542                for (sect_idx = 0; sect_idx < num_sections; ++sect_idx)
1543                {
1544                    // Iterate through the object file sections to find the
1545                    // first section that starts of file offset zero and that
1546                    // has bytes in the file...
1547                    Section *section = section_list->GetSectionAtIndex (sect_idx).get();
1548                    if (section)
1549                    {
1550                        if (m_section_load_list.SetSectionLoadAddress (section, section->GetFileAddress() + slide))
1551                            changed = true;
1552                    }
1553                }
1554            }
1555        }
1556    }
1557    return changed;
1558}
1559
1560
1561//--------------------------------------------------------------
1562// class Target::StopHook
1563//--------------------------------------------------------------
1564
1565
1566Target::StopHook::StopHook (lldb::TargetSP target_sp, lldb::user_id_t uid) :
1567        UserID (uid),
1568        m_target_sp (target_sp),
1569        m_commands (),
1570        m_specifier_sp (),
1571        m_thread_spec_ap(NULL),
1572        m_active (true)
1573{
1574}
1575
1576Target::StopHook::StopHook (const StopHook &rhs) :
1577        UserID (rhs.GetID()),
1578        m_target_sp (rhs.m_target_sp),
1579        m_commands (rhs.m_commands),
1580        m_specifier_sp (rhs.m_specifier_sp),
1581        m_thread_spec_ap (NULL),
1582        m_active (rhs.m_active)
1583{
1584    if (rhs.m_thread_spec_ap.get() != NULL)
1585        m_thread_spec_ap.reset (new ThreadSpec(*rhs.m_thread_spec_ap.get()));
1586}
1587
1588
1589Target::StopHook::~StopHook ()
1590{
1591}
1592
1593void
1594Target::StopHook::SetThreadSpecifier (ThreadSpec *specifier)
1595{
1596    m_thread_spec_ap.reset (specifier);
1597}
1598
1599
1600void
1601Target::StopHook::GetDescription (Stream *s, lldb::DescriptionLevel level) const
1602{
1603    int indent_level = s->GetIndentLevel();
1604
1605    s->SetIndentLevel(indent_level + 2);
1606
1607    s->Printf ("Hook: %d\n", GetID());
1608    if (m_active)
1609        s->Indent ("State: enabled\n");
1610    else
1611        s->Indent ("State: disabled\n");
1612
1613    if (m_specifier_sp)
1614    {
1615        s->Indent();
1616        s->PutCString ("Specifier:\n");
1617        s->SetIndentLevel (indent_level + 4);
1618        m_specifier_sp->GetDescription (s, level);
1619        s->SetIndentLevel (indent_level + 2);
1620    }
1621
1622    if (m_thread_spec_ap.get() != NULL)
1623    {
1624        StreamString tmp;
1625        s->Indent("Thread:\n");
1626        m_thread_spec_ap->GetDescription (&tmp, level);
1627        s->SetIndentLevel (indent_level + 4);
1628        s->Indent (tmp.GetData());
1629        s->PutCString ("\n");
1630        s->SetIndentLevel (indent_level + 2);
1631    }
1632
1633    s->Indent ("Commands: \n");
1634    s->SetIndentLevel (indent_level + 4);
1635    uint32_t num_commands = m_commands.GetSize();
1636    for (uint32_t i = 0; i < num_commands; i++)
1637    {
1638        s->Indent(m_commands.GetStringAtIndex(i));
1639        s->PutCString ("\n");
1640    }
1641    s->SetIndentLevel (indent_level);
1642}
1643
1644
1645//--------------------------------------------------------------
1646// class Target::SettingsController
1647//--------------------------------------------------------------
1648
1649Target::SettingsController::SettingsController () :
1650    UserSettingsController ("target", Debugger::GetSettingsController()),
1651    m_default_architecture ()
1652{
1653    m_default_settings.reset (new TargetInstanceSettings (*this, false,
1654                                                          InstanceSettings::GetDefaultName().AsCString()));
1655}
1656
1657Target::SettingsController::~SettingsController ()
1658{
1659}
1660
1661lldb::InstanceSettingsSP
1662Target::SettingsController::CreateInstanceSettings (const char *instance_name)
1663{
1664    TargetInstanceSettings *new_settings = new TargetInstanceSettings (*GetSettingsController(),
1665                                                                       false,
1666                                                                       instance_name);
1667    lldb::InstanceSettingsSP new_settings_sp (new_settings);
1668    return new_settings_sp;
1669}
1670
1671
1672#define TSC_DEFAULT_ARCH      "default-arch"
1673#define TSC_EXPR_PREFIX       "expr-prefix"
1674#define TSC_PREFER_DYNAMIC    "prefer-dynamic-value"
1675#define TSC_SKIP_PROLOGUE     "skip-prologue"
1676#define TSC_SOURCE_MAP        "source-map"
1677#define TSC_MAX_CHILDREN      "max-children-count"
1678#define TSC_MAX_STRLENSUMMARY "max-string-summary-length"
1679
1680
1681static const ConstString &
1682GetSettingNameForDefaultArch ()
1683{
1684    static ConstString g_const_string (TSC_DEFAULT_ARCH);
1685    return g_const_string;
1686}
1687
1688static const ConstString &
1689GetSettingNameForExpressionPrefix ()
1690{
1691    static ConstString g_const_string (TSC_EXPR_PREFIX);
1692    return g_const_string;
1693}
1694
1695static const ConstString &
1696GetSettingNameForPreferDynamicValue ()
1697{
1698    static ConstString g_const_string (TSC_PREFER_DYNAMIC);
1699    return g_const_string;
1700}
1701
1702static const ConstString &
1703GetSettingNameForSourcePathMap ()
1704{
1705    static ConstString g_const_string (TSC_SOURCE_MAP);
1706    return g_const_string;
1707}
1708
1709static const ConstString &
1710GetSettingNameForSkipPrologue ()
1711{
1712    static ConstString g_const_string (TSC_SKIP_PROLOGUE);
1713    return g_const_string;
1714}
1715
1716static const ConstString &
1717GetSettingNameForMaxChildren ()
1718{
1719    static ConstString g_const_string (TSC_MAX_CHILDREN);
1720    return g_const_string;
1721}
1722
1723static const ConstString &
1724GetSettingNameForMaxStringSummaryLength ()
1725{
1726    static ConstString g_const_string (TSC_MAX_STRLENSUMMARY);
1727    return g_const_string;
1728}
1729
1730bool
1731Target::SettingsController::SetGlobalVariable (const ConstString &var_name,
1732                                               const char *index_value,
1733                                               const char *value,
1734                                               const SettingEntry &entry,
1735                                               const VarSetOperationType op,
1736                                               Error&err)
1737{
1738    if (var_name == GetSettingNameForDefaultArch())
1739    {
1740        m_default_architecture.SetTriple (value, NULL);
1741        if (!m_default_architecture.IsValid())
1742            err.SetErrorStringWithFormat ("'%s' is not a valid architecture or triple.", value);
1743    }
1744    return true;
1745}
1746
1747
1748bool
1749Target::SettingsController::GetGlobalVariable (const ConstString &var_name,
1750                                               StringList &value,
1751                                               Error &err)
1752{
1753    if (var_name == GetSettingNameForDefaultArch())
1754    {
1755        // If the arch is invalid (the default), don't show a string for it
1756        if (m_default_architecture.IsValid())
1757            value.AppendString (m_default_architecture.GetArchitectureName());
1758        return true;
1759    }
1760    else
1761        err.SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
1762
1763    return false;
1764}
1765
1766//--------------------------------------------------------------
1767// class TargetInstanceSettings
1768//--------------------------------------------------------------
1769
1770TargetInstanceSettings::TargetInstanceSettings
1771(
1772    UserSettingsController &owner,
1773    bool live_instance,
1774    const char *name
1775) :
1776    InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
1777    m_expr_prefix_file (),
1778    m_expr_prefix_contents_sp (),
1779    m_prefer_dynamic_value (2),
1780    m_skip_prologue (true, true),
1781    m_source_map (NULL, NULL),
1782    m_max_children_display(256),
1783    m_max_strlen_length(1024)
1784{
1785    // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
1786    // until the vtables for TargetInstanceSettings are properly set up, i.e. AFTER all the initializers.
1787    // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
1788    // This is true for CreateInstanceName() too.
1789
1790    if (GetInstanceName () == InstanceSettings::InvalidName())
1791    {
1792        ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
1793        m_owner.RegisterInstanceSettings (this);
1794    }
1795
1796    if (live_instance)
1797    {
1798        const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
1799        CopyInstanceSettings (pending_settings,false);
1800    }
1801}
1802
1803TargetInstanceSettings::TargetInstanceSettings (const TargetInstanceSettings &rhs) :
1804    InstanceSettings (*Target::GetSettingsController(), CreateInstanceName().AsCString()),
1805    m_expr_prefix_file (rhs.m_expr_prefix_file),
1806    m_expr_prefix_contents_sp (rhs.m_expr_prefix_contents_sp),
1807    m_prefer_dynamic_value (rhs.m_prefer_dynamic_value),
1808    m_skip_prologue (rhs.m_skip_prologue),
1809    m_source_map (rhs.m_source_map),
1810    m_max_children_display(rhs.m_max_children_display),
1811    m_max_strlen_length(rhs.m_max_strlen_length)
1812{
1813    if (m_instance_name != InstanceSettings::GetDefaultName())
1814    {
1815        const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
1816        CopyInstanceSettings (pending_settings,false);
1817    }
1818}
1819
1820TargetInstanceSettings::~TargetInstanceSettings ()
1821{
1822}
1823
1824TargetInstanceSettings&
1825TargetInstanceSettings::operator= (const TargetInstanceSettings &rhs)
1826{
1827    if (this != &rhs)
1828    {
1829    }
1830
1831    return *this;
1832}
1833
1834void
1835TargetInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
1836                                                        const char *index_value,
1837                                                        const char *value,
1838                                                        const ConstString &instance_name,
1839                                                        const SettingEntry &entry,
1840                                                        VarSetOperationType op,
1841                                                        Error &err,
1842                                                        bool pending)
1843{
1844    if (var_name == GetSettingNameForExpressionPrefix ())
1845    {
1846        err = UserSettingsController::UpdateFileSpecOptionValue (value, op, m_expr_prefix_file);
1847        if (err.Success())
1848        {
1849            switch (op)
1850            {
1851            default:
1852                break;
1853            case eVarSetOperationAssign:
1854            case eVarSetOperationAppend:
1855                {
1856                    if (!m_expr_prefix_file.GetCurrentValue().Exists())
1857                    {
1858                        err.SetErrorToGenericError ();
1859                        err.SetErrorStringWithFormat ("%s does not exist.\n", value);
1860                        return;
1861                    }
1862
1863                    m_expr_prefix_contents_sp = m_expr_prefix_file.GetCurrentValue().ReadFileContents();
1864
1865                    if (!m_expr_prefix_contents_sp && m_expr_prefix_contents_sp->GetByteSize() == 0)
1866                    {
1867                        err.SetErrorStringWithFormat ("Couldn't read data from '%s'\n", value);
1868                        m_expr_prefix_contents_sp.reset();
1869                    }
1870                }
1871                break;
1872            case eVarSetOperationClear:
1873                m_expr_prefix_contents_sp.reset();
1874            }
1875        }
1876    }
1877    else if (var_name == GetSettingNameForPreferDynamicValue())
1878    {
1879        int new_value;
1880        UserSettingsController::UpdateEnumVariable (g_dynamic_value_types, &new_value, value, err);
1881        if (err.Success())
1882            m_prefer_dynamic_value = new_value;
1883    }
1884    else if (var_name == GetSettingNameForSkipPrologue())
1885    {
1886        err = UserSettingsController::UpdateBooleanOptionValue (value, op, m_skip_prologue);
1887    }
1888    else if (var_name == GetSettingNameForMaxChildren())
1889    {
1890        bool ok;
1891        uint32_t new_value = Args::StringToUInt32(value, 0, 10, &ok);
1892        if (ok)
1893            m_max_children_display = new_value;
1894    }
1895    else if (var_name == GetSettingNameForMaxStringSummaryLength())
1896    {
1897        bool ok;
1898        uint32_t new_value = Args::StringToUInt32(value, 0, 10, &ok);
1899        if (ok)
1900            m_max_strlen_length = new_value;
1901    }
1902    else if (var_name == GetSettingNameForSourcePathMap ())
1903    {
1904        switch (op)
1905        {
1906            case eVarSetOperationReplace:
1907            case eVarSetOperationInsertBefore:
1908            case eVarSetOperationInsertAfter:
1909            case eVarSetOperationRemove:
1910            default:
1911                break;
1912            case eVarSetOperationAssign:
1913                m_source_map.Clear(true);
1914                // Fall through to append....
1915            case eVarSetOperationAppend:
1916                {
1917                    Args args(value);
1918                    const uint32_t argc = args.GetArgumentCount();
1919                    if (argc & 1 || argc == 0)
1920                    {
1921                        err.SetErrorStringWithFormat ("an even number of paths must be supplied to to the source-map setting: %u arguments given", argc);
1922                    }
1923                    else
1924                    {
1925                        char resolved_new_path[PATH_MAX];
1926                        FileSpec file_spec;
1927                        const char *old_path;
1928                        for (uint32_t idx = 0; (old_path = args.GetArgumentAtIndex(idx)) != NULL; idx += 2)
1929                        {
1930                            const char *new_path = args.GetArgumentAtIndex(idx+1);
1931                            assert (new_path); // We have an even number of paths, this shouldn't happen!
1932
1933                            file_spec.SetFile(new_path, true);
1934                            if (file_spec.Exists())
1935                            {
1936                                if (file_spec.GetPath (resolved_new_path, sizeof(resolved_new_path)) >= sizeof(resolved_new_path))
1937                                {
1938                                    err.SetErrorStringWithFormat("new path '%s' is too long", new_path);
1939                                    return;
1940                                }
1941                            }
1942                            else
1943                            {
1944                                err.SetErrorStringWithFormat("new path '%s' doesn't exist", new_path);
1945                                return;
1946                            }
1947                            m_source_map.Append(ConstString (old_path), ConstString (resolved_new_path), true);
1948                        }
1949                    }
1950                }
1951                break;
1952
1953            case eVarSetOperationClear:
1954                m_source_map.Clear(true);
1955                break;
1956        }
1957    }
1958}
1959
1960void
1961TargetInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings, bool pending)
1962{
1963    TargetInstanceSettings *new_settings_ptr = static_cast <TargetInstanceSettings *> (new_settings.get());
1964
1965    if (!new_settings_ptr)
1966        return;
1967
1968    m_expr_prefix_file          = new_settings_ptr->m_expr_prefix_file;
1969    m_expr_prefix_contents_sp   = new_settings_ptr->m_expr_prefix_contents_sp;
1970    m_prefer_dynamic_value      = new_settings_ptr->m_prefer_dynamic_value;
1971    m_skip_prologue             = new_settings_ptr->m_skip_prologue;
1972    m_max_children_display      = new_settings_ptr->m_max_children_display;
1973    m_max_strlen_length         = new_settings_ptr->m_max_strlen_length;
1974}
1975
1976bool
1977TargetInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
1978                                                  const ConstString &var_name,
1979                                                  StringList &value,
1980                                                  Error *err)
1981{
1982    if (var_name == GetSettingNameForExpressionPrefix ())
1983    {
1984        char path[PATH_MAX];
1985        const size_t path_len = m_expr_prefix_file.GetCurrentValue().GetPath (path, sizeof(path));
1986        if (path_len > 0)
1987            value.AppendString (path, path_len);
1988    }
1989    else if (var_name == GetSettingNameForPreferDynamicValue())
1990    {
1991        value.AppendString (g_dynamic_value_types[m_prefer_dynamic_value].string_value);
1992    }
1993    else if (var_name == GetSettingNameForSkipPrologue())
1994    {
1995        if (m_skip_prologue)
1996            value.AppendString ("true");
1997        else
1998            value.AppendString ("false");
1999    }
2000    else if (var_name == GetSettingNameForSourcePathMap ())
2001    {
2002    }
2003    else if (var_name == GetSettingNameForMaxChildren())
2004    {
2005        StreamString count_str;
2006        count_str.Printf ("%d", m_max_children_display);
2007        value.AppendString (count_str.GetData());
2008    }
2009    else if (var_name == GetSettingNameForMaxStringSummaryLength())
2010    {
2011        StreamString count_str;
2012        count_str.Printf ("%d", m_max_strlen_length);
2013        value.AppendString (count_str.GetData());
2014    }
2015    else
2016    {
2017        if (err)
2018            err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
2019        return false;
2020    }
2021
2022    return true;
2023}
2024
2025const ConstString
2026TargetInstanceSettings::CreateInstanceName ()
2027{
2028    StreamString sstr;
2029    static int instance_count = 1;
2030
2031    sstr.Printf ("target_%d", instance_count);
2032    ++instance_count;
2033
2034    const ConstString ret_val (sstr.GetData());
2035    return ret_val;
2036}
2037
2038//--------------------------------------------------
2039// Target::SettingsController Variable Tables
2040//--------------------------------------------------
2041OptionEnumValueElement
2042TargetInstanceSettings::g_dynamic_value_types[] =
2043{
2044{ eNoDynamicValues,      "no-dynamic-values", "Don't calculate the dynamic type of values"},
2045{ eDynamicCanRunTarget,  "run-target",        "Calculate the dynamic type of values even if you have to run the target."},
2046{ eDynamicDontRunTarget, "no-run-target",     "Calculate the dynamic type of values, but don't run the target."},
2047{ 0, NULL, NULL }
2048};
2049
2050SettingEntry
2051Target::SettingsController::global_settings_table[] =
2052{
2053    // var-name           var-type           default      enum  init'd hidden help-text
2054    // =================  ================== ===========  ====  ====== ====== =========================================================================
2055    { TSC_DEFAULT_ARCH  , eSetVarTypeString , NULL      , NULL, false, false, "Default architecture to choose, when there's a choice." },
2056    { NULL              , eSetVarTypeNone   , NULL      , NULL, false, false, NULL }
2057};
2058
2059SettingEntry
2060Target::SettingsController::instance_settings_table[] =
2061{
2062    // var-name             var-type            default         enum                    init'd hidden help-text
2063    // =================    ==================  =============== ======================= ====== ====== =========================================================================
2064    { TSC_EXPR_PREFIX       , eSetVarTypeString , NULL          , NULL,                  false, false, "Path to a file containing expressions to be prepended to all expressions." },
2065    { TSC_PREFER_DYNAMIC    , eSetVarTypeEnum   , NULL          , g_dynamic_value_types, false, false, "Should printed values be shown as their dynamic value." },
2066    { TSC_SKIP_PROLOGUE     , eSetVarTypeBoolean, "true"        , NULL,                  false, false, "Skip function prologues when setting breakpoints by name." },
2067    { TSC_SOURCE_MAP        , eSetVarTypeArray  , NULL          , NULL,                  false, false, "Source path remappings to use when locating source files from debug information." },
2068    { TSC_MAX_CHILDREN      , eSetVarTypeInt    , "256"         , NULL,                  true,  false, "Maximum number of children to expand in any level of depth." },
2069    { TSC_MAX_STRLENSUMMARY , eSetVarTypeInt    , "1024"        , NULL,                  true,  false, "Maximum number of characters to show when using %s in summary strings." },
2070    { NULL                  , eSetVarTypeNone   , NULL          , NULL,                  false, false, NULL }
2071};
2072